Gero
Gero

Reputation: 13563

How to read a json without a value with Gson?

I read a json file with the GSON library. I use the following code:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

Everything works fine, if my json has all values, but if there are some values missing in the json, such as the following json, I get an Exception.

com.google.gson.stream.MalformedJsonException: 
Expected value at line 1 column 217 path $.repeatInterval

.

{
  "key1": "a",
  "key2": "",
  "key3": 
}

How can I read a json file with missing values when using GSON library?

edit: Solution without exception. Add "key3:""

{
  "key1": "a",
  "key2": "",
  "key3": ""
}

Upvotes: 0

Views: 79

Answers (1)

Filip
Filip

Reputation: 2344

Your json is invalid as you can see on this site for instance: http://jsonlint.com/ As far as I know, GSON will always throw exception on invalid JSON, and that is intended behavior. If you can create that JSON, try at least to put "" instead of empty value in order to comply with JSON format.

Upvotes: 1

Related Questions