Search code examples
javaandroidgsonpojo

POJO for JSON array without keys [Long, Double]


I have this JSON:

{
    "entries": [
        [
            1545230391429,        // long
            3799.9872120695404    // double
        ],
        [
            1545230685249,
            3796.6928339346546
        ],
        [
            1545231000586,
            3793.6487491594485
        ],
        ...
    ]
}

This POJO can handle them as Strings, but then I need to manually convert them to proper types... aaaand it's risky:

@SerializedName("entries")
@Expose
private List<List<String>> entries;

I tried with more robust way, but it's not working properly:

public class Entry {
    public Long timestamp;
    public Double value;
}

@SerializedName("entries")
@Expose
private List<Entry> entries;

I get

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 13 path $.entries[0]

I think the problem is that Entry should be a List, but I can't make a list with two different types.

How to proceed?


Solution

  • MyData Class

    @SerializedName("entries")
    @Expose
    private List<List<String>> entries;
    

    Try with a custom deserialized (this is just a sample, check the code)

    JsonDeserializer<MyData> deserializer = new JsonDeserializer<MyData>() {  
        @Override
        public MyData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    
            List myList = new ArrayList<Entry>()
    
            JSONArray arr = obj.getJSONArray("entries");
    
            for (int i = 0; i < arr.length(); i++) {
              Entry entry = new Entry(
                    new Long(arr[0]),
                    new Long(arr[1])
              );
              myList.add(entry)
            }
    
    
    
            return new MyData(myList);
        }
    };