4

I have a problem with one type of JSON.

Example:

{
   "1": "name",
   "2": "example",
   "3": "loremipsum",
   "4": "etc",
}

I'm always converting json to POJO with Gson. I'm using Retrofit 1.9

But in this case its stupid because I receive object like:

public class Example {

    @SerializedName("1")
    @Expose
    private String _1;
    @SerializedName("2")
    @Expose
    private String _2;
    @SerializedName("3")
    @Expose
    private String _3;
    @SerializedName("4")
    @Expose
    private String _4;
    .........

How can I parse this JSON to receive list of objects like:

public class Example {
    private int id;
    private String value;
}

Thanks for help.

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
MobileDev
  • 165
  • 2
  • 11

3 Answers3

1

If your JSON has variable keys, you have to deserialize it by hand so I think the best solution is changing your JSON response to:

    [
      {"id" : 1, "value" : "name"}, 
      {"id" : 2, "value" : "example"}
    ]

and

public class Response {
    public Example[] examples;
}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
Héctor
  • 24,444
  • 35
  • 132
  • 243
0

Because your variable keys, it's hard to parse with GSON.

But you can use JSONObject to do this, and it's really simple. There is the code, I had test it, it works great:

private ArrayList<Example> parseJson() throws JSONException {
    String json = "{\n" +
            "   \"1\": \"name\",\n" +
            "   \"2\": \"example\",\n" +
            "   \"3\": \"loremipsum\",\n" +
            "   \"4\": \"etc\"\n" +
            "}";

    ArrayList<Example> exampleList = new ArrayList<>();
    JSONObject jsonObject = new JSONObject(json);
    Iterator<String> iterator = jsonObject.keys();
    while(iterator.hasNext()) {
        Example example = new Example();
        String id = iterator.next();
        example.id = Integer.parseInt(id);
        example.value = jsonObject.getString(id);

        exampleList.add(example);
    }
    return exampleList;
}
L. Swifter
  • 3,179
  • 28
  • 52
0

I found solution:

I used Gson.JsonObject as response

And later:

  Type type = new TypeToken<Map<String, String>>(){}.getType();
  Map<String, String> myMap = new Gson().fromJson(jsonObject.toString(), type);
MobileDev
  • 165
  • 2
  • 11