JSON parsing using Google GSON: reading values ​​directly from child objects

I am having trouble parsing the following JSON with Google Gson:

{"Name":
    {"object1":   
       {"field1":"17",
        "field2":"360",
        "field3":"19",
        "field4":"sun",
        "field5":"rain"
       }
    }
}

I tried the following to get the value of field1, but it does not work.

@SerializedName("Name/object1/field1")
public int fieldOne;

What am I doing wrong?

+1
source share
3 answers

Your objects should maintain a hierarchy of your json instructions. For your example, it would be something like this:

public class Object {

    @SerializedName("field1")
    public String fieldOne;

    @SerializedName("field2")
    public String fieldTwo;

    @SerializedName("field3")
    public String fieldThree;

    @SerializedName("field4")
    public String fieldFour;
}

public class Name {

    @SerializedName("object1")
    public Object obj;
}

public class GsonObj {

    @SerializedName("Name")
    public Name name;
}

Using the following call:

String json = "{\"Name\":{" +
            "\"object1\":{" +
            "\"field1\":\"17\",\"field2\":\"360\",\"field3\":\"19\",\"field4\":\"sun\",\"field5\":\"rain\"}}}";

Gson gson = new Gson();
GsonObj jsonResult = gson.fromJson(json, GsonObj.class);
Log.d("test", "field one: "+jsonResult.name.obj.fieldOne);
Log.d("test", "field two: "+jsonResult.name.obj.fieldTwo);
Log.d("test", "field three: "+jsonResult.name.obj.fieldThree);
Log.d("test", "field four: "+jsonResult.name.obj.fieldFour);
+3
source

You have invalid json. JSON can start with {or [so you need to wrap your string with another pair {}.

. : http://jsonlint.com/

+1

I do not think that you can have "Name / object1 / field", you should specify the key name directly without hierarchy. refer How do I parse JSON dynamic fields using GSON?

0
source

Source: https://habr.com/ru/post/1584407/


All Articles