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.