I have a simple class containing name
variable of type java.lang.CharSequence
class Person {
public java.lang.CharSequence name;
}
When I try to deserialize a JSON String using GSON library
Person p;
Gson gson = new Gson();
String json = "{\"name\":\"dinesh\"}";
p = gson.fromJson(json, Person.class);
System.out.println(p);
It gives me the following error:
java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.CharSequence. Registering an InstanceCreator with Gson for this type may fix this problem.
How do I fix this? I cannot change the Person.name
type to String
.
As suggested in comments,
I created a custom adapter for CharSequence
class CharSequenceAdapter extends TypeAdapter<CharSequence> {
@Override
public void write(JsonWriter out, CharSequence value) throws IOException {
}
@Override
public CharSequence read(JsonReader in) throws IOException {
String s = new String();
in.beginObject();
while(in.hasNext()) {
s = in.nextString();
}
return s;
}
}
And my GSON builder looks like this:
Person p;
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(java.lang.CharSequence.class, new CharSequenceAdapter());
Gson gson = builder.create();
String json = "{\"name\":\"dinesh\"}";
p = gson.fromJson(json, Person.class);
System.out.println(p);
Now it gives me another error:
Expected BEGIN_OBJECT but was STRING at line 1 column 10 path $.name
What did I miss?
I don't think it's a duplicate. All the other questions talk about deserializing one class or interface as a whole. I am having a problem with a class that has interface references as member variables. I couldn't solve the problem from similar answers.
CharSequence is an interface.
When Gson tries to deserialize a json string into an object it “introspects” the object (by using reflection) and tries to resolve the types of fields. Then it tries to create a field of that time.
Out of the box Gson can deal with many “widespread” types like String, Integer, Boolean and so forth, however when its something GSon is not aware of (Like CharSequence in this case), GSon stops with Error.
Now its clear that you should “teach” Gson to understand this custom type. For this purpose there are type adapters in Gson.
Here you can find a short tutorial on using the adapters. I won’t re-write here an example from there, but in general you should create an adapter, register it on Gson object and call your code. When Gson reaches the CharSequence field it will find this custom adapter and invoke it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With