0

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.

8
  • 1
    What if you replace the null for d with "" Commented Apr 12, 2018 at 23:16
  • thats an empty sting, but I need a null object. Commented Apr 12, 2018 at 23:21
  • What does your my class look like Commented Apr 12, 2018 at 23:22
  • 1
    And your A class? Commented Apr 12, 2018 at 23:42
  • 1
    hope this helps you stackoverflow.com/a/24252578/4598342 Commented Apr 13, 2018 at 4:10

2 Answers 2

1

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

Comments

1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.