Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert json objects with number as field key in Java?

Tags:

java

json

gson

The server I am working with returns an json object which contains a list of objects, not just one.

{
"1":{"id":"1","value":"something"},
"2":{"id":"2","value":"some other thing"}
}

I want to convert this json object into an object array.

I know I can use Gson, and create a class like this:

public class Data {
    int id;
    String value;
}

and then use

Data data = new Gson().fromJson(response, Data.class);

But it's only for the objects inside the json object. I don't know how to convert json object with number as keys.

Or alternatively I need to alter the server to response to something like this?:

{["id":"1","value":"something"],["id":"2","value":"some other thing"]}

But I don't want to change to server as I have to change all the client side codes.

like image 937
Kyle Xie Avatar asked Jul 24 '13 03:07

Kyle Xie


1 Answers

Your JSON looks really weird. If you can't change it, you have to deserialize it to Map. Example source code could looks like this:

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class GsonProgram {

    public static void main(String... args) throws Exception {
        Gson gson = new GsonBuilder().create();
        String json = "{\"1\":{\"id\":\"1\",\"value\":\"something\"},\"2\":{\"id\":\"2\",\"value\":\"some other thing\"}}";

        Type type = new TypeToken<HashMap<String, HashMap<String, String>>>() {}.getType();
        Map<String, Map<String, String>> map = gson.fromJson(json, type);
        for (Map<String, String> data : map.values()) {
            System.out.println(Data.fromMap(data));
        }
    }
}

class Data {

    private int id;
    private String value;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Data [id=" + id + ", value=" + value + "]";
    }

    public static Data fromMap(Map<String, String> properties) {
        Data data = new Data();
        data.setId(new Integer(properties.get("id")));
        data.setValue(properties.get("value"));

        return data;
    }
}

Above program prints:

Data [id=2, value=some other thing]
Data [id=1, value=something]
like image 147
Michał Ziober Avatar answered Oct 02 '22 15:10

Michał Ziober