Empty json object instead of null, when no data -> how to deserialize with gson
Solution 1
Can't you just replace {} with NULL before passing it to the GSON?
Solution 2
Make your TypeAdapter<String>
's read
method like this:
public String read(JsonReader reader) throws IOException {
boolean nextNull = false;
while (reader.peek() == JsonToken.BEGIN_ARRAY || reader.peek() == JsonToken.END_ARRAY) {
reader.skipValue();
nextNull = true;
}
return nextNull ? null : reader.nextString();
}
Explain: when next token is [
or ]
, just skip it and return null.
If you replace all []
to null
use String#replaceAll
directly, some real string may be replaced as well, This may cause some other bugs.
msal
Intelligence is the ability to avoid doing work, yet getting the work done. - Linus Torvalds
Updated on June 07, 2022Comments
-
msal almost 2 years
I am trying to parse json data with Google's gson library. But the json data doesn't behave well.
It does look like this when everything is alright:
{ "parent": { "child_one": "some String", "child_two": "4711", ... } }
child_one
should be parsed asString
,child_two
asint
. But sometimes one of the children has no values what results in an empty object instead ofnull
, like this:{ "parent": { "child_one": "some String", "child_two": {}, ... } }
I have no access to alter the json feed, so I have to deal with it during deserialization. But I am lost here. If I just let it parse the 2nd case gives me a
JsonSyntaxException
.I thought about using a custom
JsonDeserializer
. Do there something like inspect every element if it is aJsonObject
and if it is, check if theentrySet.isEmpty()
. If yes, remove that element. But I have no idea how to accomplish the iterating... -
Sotirios Delimanolis over 10 years
null
would still be invalid as OP has to parse toint
. -
msal over 10 years@Adassko That was the right idea. I simply had to do this to the data, before passing it:
json.toString().replace("{}", "null");
-
msal over 10 years@SotiriosDelimanolis
null
is fine, as gson handles the parsing. :) -
sulhadin almost 5 yearsKey can also be an object or an array. So it is not useful to run replace().
-
JHH about 4 yearsHow this seriously could be the accepted answer is beyond me. Instead of writing code that successfully parses JSON containing empty objects - which is perfectly valid - you're suggesting manually avoiding it by string substitution before parsing?