2

I'm having trouble parsing the following JSON with Google's Gson:

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

I have tried the following to get the value of field1 but it doesn't work

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

What am I doing wrong?

Jonik
  • 80,077
  • 70
  • 264
  • 372
Dave
  • 783
  • 3
  • 15
  • 25
  • 1
    +1. Kind of surprising that Gson doesn't seem to have a notation like `@SerializedName("Name/object1")` or `@SerializedName("Name.object1")` for getting values from child objects directly. – Jonik Oct 25 '13 at 15:16
  • (Btw, removed Android tag as this is not Android specific at all.) – Jonik Oct 25 '13 at 15:19

3 Answers3

3

Your objects have to conserve the 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);
Michel-F. Portzert
  • 1,785
  • 13
  • 16
1

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

A good practice is to always check your data first. I often use this here: http://jsonlint.com/

Kai Mattern
  • 3,090
  • 2
  • 34
  • 37
0

I don't think you can have "Name/object1/field" you have to specify key name directly without hierarchy. refer How to parse dynamic JSON fields with GSON?

Community
  • 1
  • 1
Taranfx
  • 10,361
  • 17
  • 77
  • 95