简体   繁体   中英

Parse json string to object using Gson

I tried converting my json string to java object by using Gson but somehow it was not successful and I haven't figured out why..

My Json string

{
    "JS":{
        "JS0":{
            "Name":"ABC",
            "ID":"5"
        },
        "JS1":{
            "Location":"UK",
            "Town":"LD"
        },
        "JS2":{
            "Usable":"true",
            "Port":"ABC"
        }
    }
}

In java code I have 4 classes, JS, JS0, JS1 and JS2
JS class contains JS0, JS1 and JS2 variables
JS0, JS1 and JS2 classes contain fields as in Json string example, eg JS0 contains 02 fields, String Name and String ID
In all classes I have getter/setter for variables, 02 constructors (01 with empty parameters and another one with all variables in the parameter field)


And for using Gson:

Gson gson = new Gson();
jsObject = gson.fromJson(sb.toString(), JS.class);


When I access JS0, JS1 and JS2 objects from jsObject, they are null...
Can someone show me what did I do wrong?
Thank you very much,

The problem here is, you are trying to convert

{
   "JS" : {
       /* rest of JSON */
   }
}

to JS object, but the above JSON is a representation of Java class like this

class Foo {
   JS JS;
}

So, you need to get the value of JS from the JSON string first, then call fromJSON to deserialize it with the JS.class passed as the second parameter.

OR

Create a simple class containing only JS as a variable, then call fromJSON with that class passed as the second parameter of fromJSON like this:

Java

class Foo {
   JS JS;
}


jsObject = gson.fromJson(sb.toString(), Foo.class);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM