Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to add a String as a property to JsonObject using add()

I have a com.google.gson.JsonObject and Iam trying to add a String directly to the object using add() menthod. Below given is the code I am using

JsonObject jsonobject = new JsonObject();
jsonobject.add("Name", JsonParser.parseString("AAAA").getAsJsonObject());

The above code is giving me the below error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

java.lang.IllegalStateException: Not a JSON Object: "AAAA"

Could someone please tell me what am I doing wrong here?

Thanks in advance for the help!!

>Solution :

I am not familiar with the library but too my programmer eyes it looks like you are trying to CREATE a JSON object using JsonObject and add a key-value pair to it by using its .add() method. I would assume this class and this method simply expects a key and a value, in your case both would be strings. I checked, its value should be JsonElement, so if you would want to use this, you should drop the .toJsonObject() call, but it still won’t work as you want, read on.

Your key is correct but then the value is where I believe it goes wrong. You try to create (parse) another JSON object from a simple string ("AAAA"). The parse method expects a valid JSON-object in string format, for example

{ "Name": "FooBar" }

As you can understand, it has already gone wrong at this point as you provide a string which is not a JSON object string. But to "make things worse", you then also try to convert the JsonElement returned by the parse, into a JsonObject which then you want to add as your value in the add() function. Now, as I said, the parse already fails so this extra toJsonObject() does not really make a difference.

What I think you want to do is the following

JsonObject jsonobject = new JsonObject();
jsonobject.addProperty("Name", "AAAA");

Notice the .addProperty(string key, string value) method. This is probably what you are looking for. If you really are trying to add another JSON object as the value, you need to make sure the string you are giving is a valid JSON object rather than a simple trivial string.

Check out the documentation: https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonObject.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading