I've recently started using GSON library for deserializing JSON that comes from web service but I can't make it work. I decide to test GSON on some simple input - can't make it any simpler and it still doesn't work. I've looked through similar issues like Converting JSON to Java, all of which suggest similar approach to solution. My guess is that I'm missing something really simple and obvious so a fresh view on the code would probably help. So here is what I have:
JSON
{"A":{"name":"qwrety","value1":1,"value2":2}}
Java class
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String json = /*getting JSON from server*/
Gson gson = new Gson();
A obj = gson.fromJson(json, A.class);
System.out.println(obj);
}
}
class A {
private String name;
private int value1;
private int value2;
public String getName() { return name; }
public int getValue1() { return value1; }
public int getValue2() { return value2; }
public void setName(String name) { this.name = name; }
public void setValue1(int value1) { this.value1 = value1; }
public void setValue2(int value2) { this.value2 = value2; }
public String toString() {
return String.format("name: %s, value1: %d, value2: %d", name, value1, value2);
}
}
What I get in return is
name: null, value1: 0, value2: 0
Anyone can tell what is wrong with this code?
UPD As @torbinsky and @Kevin-Dolan pointed out, the problem was because Java class structure didn't match the Json format. To fix this I added a new class
class Container {
private A a;
public A getA() { return a; }
public void setA(A a) { this.a = a; }
}
and changed the deserialisation call to following
Gson gson = new Gson();
Container obj = gson.fromJson(json, Container.class);
System.out.println(obj.getA());
However I anyway get "null" printed out