Reputation: 814
I have a Java class:
public class Object1 {
private int field1;
private String field2;
private Object2 object2;
private boolean field3;
}
I've saved some Object1 instance as JSON string using Gson:
String jsonString = new Gson().toJson(object1, Object1.class);
And then I added new String field to Object1 class:
public class Object1 {
private int field1;
private String field2;
private String field4;
private Object2 object2;
private boolean field3;
}
And now I can't to deserialize json string to Object1 instance using method:
Object1 obj1 = new Gson().fromJson(jsonString, Object1.class);
Because of Gson throws exception:
System.err: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 444 path $.c at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224) at com.google.gson.Gson.fromJson(Gson.java:887) at com.google.gson.Gson.fromJson(Gson.java:852) at com.google.gson.Gson.fromJson(Gson.java:801) at com.google.gson.Gson.fromJson(Gson.java:773)
But why? I have JSON string without one field and it can't to be a problem. Why I can't deserialize it?
Upvotes: 0
Views: 1695
Reputation: 814
As it turned out problem was in obfuscation.
If you're not use @SerializedName annotation result JSON can be like that:
{"a":3436213,"b":"some string","c":{.............},"d":true}
We didn't use it because of it isn't DTO. In this case we using JSON just to store some unimportant internal data. But it was very funny lesson for me.
Upvotes: 0
Reputation: 1690
Expected a string but was BEGIN_OBJECT
field4
in your json string is not of type String, use a Json to POJO generator to create a proper object.
I like to use http://www.jsonschema2pojo.org/
Upvotes: 0