I am trying to take a json and convert it into a POJO using Gson's ability. I got it working with the serialized class as a class in a separate package, but now I am trying to get the serialized class to be an inner class of the class which is calling it, kind of like how I have depicted below.
public class A {
private final Gson gson;
public A() {
gson = new GsonBuilder().serializeNulls().create();
}
public void foo(String json){
B b = gson.fromJson(json, B.class);
}
public static class B {
private String bar;
public String getBar(){
return bar;
}
}
}
Sample JSON:
{"bar": "test"}
This setup returns null values for the inner class variables; in this case, just bar. I've made sure the json being passed in matches the names of variables in Class B, in this example. Additionally, I have experimented around with making the inner class non-static and private with no success. To my understanding it needs to be a static class in order for it to be serialized using gson. Is there anything blatantly obvious that I am doing wrong that you can see?
The error is somewhere else. Most probably the String
or the Gson
you pass is configured the wrong way. I pasted the exact same code and it works fine for me:
public class Main {
public static void main (String[] args) {
new A().foo("{\"bar\": \"test\"}");
}
public static class A {
private final Gson gson;
public A() {
gson = new GsonBuilder().serializeNulls().create();
}
public void foo(String json){
B b = gson.fromJson(json, B.class);
System.out.println(b);
}
public static class B {
private String bar;
public String getBar(){
return bar;
}
@Override
public String toString() {
return "B{bar='" + bar + '\'' +
'}';
}
}
}
}
Inner classes are supposed to work so the problem is elsewhere. This will print out:
B{bar='test'}
So I imagine this is a common issue, now that I've run into it twice. The issue was in the JSON string being passed in. I copied and pasted the JSON from somewhere into the command line. As a result, the quotations weren't being registered as valid quotation marks. It was “
as opposed to "
. The second is what is registered as a quotation mark. Thanks for all the help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.