1

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, e.g. 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,

3
  • Are you sure your pojo variable matches the json? Commented May 18, 2015 at 12:05
  • Yes I check every single of them and they are totally matched .. Commented May 18, 2015 at 12:08
  • @Xitrum see the below answer Commented May 18, 2015 at 12:39

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.