I want to copy one primitve property from one JsonObject to another
JsonObject propertyToBeCopied = source.getAsJsonObject(propertyName);
but I always run into this exception:
com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject
According to the documentation it should be possible to do the cast, or am I wrong?
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
JSONObject is "native" to Android SDK, JsonObject is probably the one from Gson library, the one that I use. Two different package, don't work with both ;) choose one. I had some issue with the date formatting in JSONObject.
JSONNull is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined. Author: JSON.org See Also: Serialized Form. Method Summary. boolean. equals(Object object)
A JSONObject can parse text from a String to produce a map-like object and a JSONArray can parse text from a String to produce a vector-like object. We can also add a JSONArray within JSONObject by first creating a JSONArray with few items and add these array of items to the put() method of JSONObject class.
According to the docsJsonNull
is a JsonElement
but not a JsonObject
(which is itself a JsonElement
). Using
JsonElement element = source.get(propertyName);
if (!(element instanceof JsonNull)) {
JsonObject propertyToBeCopied = (JsonObject) element;
}
would return a JsonElement
that is casted to JsonObject
if it is not of the type JsonNull
.
JsonElement element = source.get(propertyName);
if (!(element.isJsonNull())) {
JsonObject propertyToBeCopied = (JsonObject) element;
}
Which one will have better performance isJsonNull or using instanceOf operator ?
According to the API reference, JsonNull
derives from JsonElement
and not JsonObject
, so I don't see how that cast could ever be valid.
And have you considered using json-simple instead of gson? As a general rule I find it much more convenient to work with than other json frameworks, although of course it doesn't have a lot of the extra features that gson offers. But if all you're doing with gson is parsing json, it might be worth switching to the simpler library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With