JsonSyntax exception due to IllegalState of gson

I have weird behavior when parsing json with gson. I am using this code:

private static Container parseContainer(String containerJson) { try { //TODO Remove try catch when Bug is done return containerJson != null ? new Gson().fromJson(containerJson, Container.class) : null; } catch (JsonSyntaxException e) { LOGGER.error("JsonSyntaxException ", e); LOGGER.error("Json: " + containerJson); //Sleep 3 minutes and try again. try { Thread.sleep(1000L * 60 * 3); } catch (InterruptedException e1) { LOGGER.error("Exception", e); } LOGGER.error("Try again to parse json: " + containerJson); Container result = new Gson().fromJson(containerJson, Container.class); LOGGER.error("Parsing successful on second try."); return result; } } 

When a method is called in my project, it usually works without exception. But sometimes an exception is thrown, and after waiting for a while, parsing works fine.

I did not understand when the exception was thrown, and when not.

How can a journal be registered in the journal Analysis Successful on Second Attempt?

The exception is

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapt erFactory.java:176) at com.google.gson.Gson.fromJson(Gson.java:803) at com.google.gson.Gson.fromJson(Gson.java:768) at com.google.gson.Gson.fromJson(Gson.java:717) at com.google.gson.Gson.fromJson(Gson.java:689) 
+5
source share
1 answer

Your exception is not filled. There must be comments in IllegalStateException. Something like that.

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 

It would be more useful if you could see it in this format. So, anyway, an error that your Container.class () is not suitable for your Json container, try fixing it with code like this

 Type collectionType = new TypeToken<Collection<Container>>(){}.getType(); Collection<Container> enums = gson.fromJson(containerJson, collectionType); 
0
source

Source: https://habr.com/ru/post/1208723/


All Articles