i am attempting to turn a json string into objects with gson.
I have a very simple example below, and it runs, but the resulting answer is empty, ie: my Answer objects’s text field is empty.
import com.google.gson.*;
public class Meow {
public static void main(String[] args) throws Exception{
Gson gson = new Gson();
String jsonOutput = "[{\"answer\":{\"text\":\"text1\"}},{\"answer\":{\"text\":\"text2\"}} ]";
Answer[] a = gson.fromJson(jsonOutput, Answer[].class);
for(Answer i:a) {
System.out.println(i.text);
}
}
public class Answer {
public String text;
public Answer(String text) {
super();
this.text=text;
}
public String toString(){
return text;
}
public void setText(String a){
this.text=a;
}
}
}
Because your JSON doesn’t match your class.
Your JSON right now is an array of objects, each containing an
answerobject as a field.Your JSON the way you have things would need to look like:
Edit to add from comments:
If you can’t change the output, you need a “wrapper”. Something like:
And use an array of those. That is what the JSON will map to. It can’t see them as
Answerobjects because … they’re not.One More Edit to Add: Your other option is to write custom deserializers for your classes. I’m a bit mixed on whether you should do this or not, but it will work. The reason I say that is that you have JSON that isn’t an array of
Answerobjects, but you want it to be. I think I’d be annoyed if I came across this in production code because without understanding what was going on it could be confusing.With that caveat being said, you can create a custom
JsonDeserializerand useGsonBuilder:Then your code would look like:
If it were me, and I had JSON that wasn’t what I needed it to be but wanted to use GSON to directly serialize/deserialize I’d create the
Answerclass as a wrapper that hid the details:With the public getters/setters for
Answeraccessing the privateRealAnswer. It just seems way cleaner and easier to understand for the next guy.