GSON avoids JsonSyntaxException returns partial mapping

I get this problem, I don’t want to solve this problem, but find a way to tell GSON to “skip errors and continue” parsing:

Can't parses json : java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 16412 

Used code:

 JsonReader reader = new JsonReader(new StringReader(data)); reader.setLenient(true); Articles articles = gson.create().fromJson(reader, Articles.class); 

Data (for simplification): Article-> Pages-> medias.fields. One field in the current error is defined as a string, but I get an object (but again, this is only one occurrence). I cannot add protection everywhere, so my question is: is there a pass and continues in GSON?

I want to avoid JsonSysntaxException using GSON when there is a problem on node, and I expect that at least you will get parsed partial data. In my case, I would have 99.999% of the data, and only my wrong field would be null ... I know this doesn't seem clean, but I would enable "strict mode" for unit test or continuous integration to detect the problem and produce I will enable soft mode so that my application can start (even when the server side made errors). I can’t say that your application cannot be started, because the article contains invalid data.

Does GSON skip and continue by mistake?

+6
source share
2 answers

I think the answer is simple: no, usually this is not possible.

Due to the recursive parsing of the library, if something is wrong, this may cause some kind of exception. It would be interesting if you could post SSCCE of your problem to experiment, if you could create a custom adapter of the type that handles the best exceptions.

+2
source

Here is the solution: You should create a TypeAdapterFactory that allows you to intercept the TypeAdapter by default, but still leave you the default TypeAdapter access as a delegate. Then you can just try to read the value using the delegate from the TypeAdapter by default, and handle the unexpected data as you wish.

  public Gson getGson() { return new GsonBuilder() .registerTypeAdapterFactory(new LenientTypeAdapterFactory()) .create(); } class LenientTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } public T read(JsonReader in) throws IOException { try { //Here is the magic //Try to read value using default TypeAdapter return delegate.read(in); } catch (JsonSyntaxException e) { //If we can't in case when we expecting to have an object but array is received (or some other unexpected stuff), we just skip this value in reader and return null in.skipValue(); return null; } } }; } } 
+1
source

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


All Articles