How to resolve MalformedJsonException: Unterminated object that exist even after setting JsonReader to lenient

krishna picture krishna · May 14, 2019 · Viewed 8.6k times · Source

I am trying to parse two json files and convert them to Map<String, Object> using gson but while doing the above convertion using gson i am getting com.google.gson.stream.MalformedJsonException: Unterminated object exception.

I have my json file like below:

{"obj":
    {
        "thumbnail":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAACQCAYAAABeUmTwAAAW==",
        "file":"2",
        "CreatedOn":"Mon May 13 16:24:52 IST 2019"
    },
    "Status":"Created",
    "Modified":"false",
    "Tags":{"Business":"No","Entertainment":"Yes"}
}

The problem is if there is some space in json object or ":" then it is throwing that error, I have tried setting JsonReader to Lenient as well but that also didnot help

And i have tried with the below code:

    JSONParser parser1 = new JSONParser(new FileReader("D:/New Folder/2.json"));
    Object obj1 = parser1.parse();

    JsonReader reader1 = new JsonReader(new StringReader(obj1.toString()));
    reader1.setLenient(true);

    Type mapType = new TypeToken<Map<String, Object>>(){}.getType();

    Map<String, Object> firstMap = gson.fromJson(reader1, mapType);

It is throwing me the below Exception

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 22 path $..thumbnail


at com.google.gson.Gson.fromJson(Gson.java:942)
    at com.cts.ciqd.gitpoc.Git.Poc.test.FlatMapUtil.main(FlatMapUtil.java:85)
Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 22 path $..thumbnail
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:491)
    at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414)
    at com.google.gson.internal.bind.ObjectTypeAdapter.read(ObjectTypeAdapter.java:69)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
    at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    ... 1 more

Is there any thing else i should do to overcome the exception?

Answer

amazia picture amazia · May 14, 2019

im not sure why you need the JsonParser and reader in this use case.

i think you can accomplish what you wanted in the following:

byte[] encoded = Files.readAllBytes(Paths.get("<your path>"));
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = new Gson().fromJson(new String(encoded, Charset.defaultCharset()), mapType);

and make sure that the json is valid