Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple Json to Java convertion using GSON
    primarykey
    data
    text
    <p>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 <a href="https://stackoverflow.com/questions/1688099/converting-json-to-java/">Converting JSON to Java</a>, 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:</p> <p>JSON</p> <pre><code>{"A":{"name":"qwrety","value1":1,"value2":2}} </code></pre> <p>Java class</p> <pre><code>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); } } </code></pre> <p>What I get in return is </p> <pre><code>name: null, value1: 0, value2: 0 </code></pre> <p>Anyone can tell what is wrong with this code?</p> <p><strong>UPD</strong> 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 </p> <pre><code>class Container { private A a; public A getA() { return a; } public void setA(A a) { this.a = a; } } </code></pre> <p>and changed the deserialisation call to following</p> <pre><code>Gson gson = new Gson(); Container obj = gson.fromJson(json, Container.class); System.out.println(obj.getA()); </code></pre> <p>However I anyway get "null" printed out</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload