anotherCoder
anotherCoder

Reputation: 732

GSON converting json to class object

My json:

{
  "d": {
    "a": {
      "someId": null,
      "e": "8"
    },
    "p": {
      "m": "t"
    }
  }
}

I am using

gson.fromJson(ResourceUtils.getStringFromInputStream(inputStream), MyClass.class);

MyClass

{
public D d;
}

D {
public A a;
public P p;
}

A {
public String someId;
public String e;
}

P {
public String m;
}

But when I run it:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was NULL at path $.someId

So basically I want to create an object from the json file in android app. I am using gson for that. But the null value isn't getting set properly.

Upvotes: 0

Views: 872

Answers (2)

mahsa_azizy
mahsa_azizy

Reputation: 37

You can use from http://www.jsonschema2pojo.org/ to convert json to java class.

and convert Gson to json : new Gson().tojson()

Upvotes: 1

Davide Patti
Davide Patti

Reputation: 3471

The Gson default behavior is to "ignore" the null properties. You can change this behavior calling the serializeNulls:

Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.

Example:

public static void main (String args[])
    {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls();
        Gson gson = gsonBuilder.create();
        String filename="path2/theJsonFile";
        try {
            JsonReader read= new JsonReader(new FileReader(filename));
            MyClass myclass= gson.fromJson(read, MyClass.class);
            System.out.println(gson.toJson(myclass));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

The output will be:

{"d":{"a":{"someId":null,"e":"8"},"p":{"m":"t"}}}

Upvotes: 1

Related Questions