I recently started using the GSON library for JSON deserialization that comes from a web service, but I can't get it to work. I decided to test GSON on some simple input - it cannot make it simpler, and it still doesn't work. I looked at similar issues, such as Converting JSON to Java , all of which offer a similar approach to the solution. I guess I missed something really simple and obvious, so a fresh look at the code will 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 = 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
name: null, value1: 0, value2: 0
Can anyone tell what is wrong with this code?
UPD As @torbinsky and @ Kevin-Dolan pointed out, the problem was that the structure of the Java class did not conform to 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 deserialization call to
Gson gson = new Gson(); Container obj = gson.fromJson(json, Container.class); System.out.println(obj.getA());
However, I still get a "zero" fingerprint