使用动态密钥序列化JSON响应

时间:2018-12-15 16:10:44

标签: java android json serialization gson

我有以下Json字符串,需要将其序列化为POJO对象:

{"pump_6":{"name":"Pump 6","value":"tequila","pin":25},"pump_5":{"name":"Pump 5","value":"vodka","pin":24},"pump_4":{"name":"Pump 4","value":"oj","pin":23},"pump_2":{"name":"Pump 2","value":"gin","pin":27},"pump_1":{"name":"Pump 1","value":"rum","pin":17},"pump_3":{"name":"Pump 3","value":"coke","pin":22}}

您看到的键是动态的(pump_6,pump_5)。我尝试了不同的解决方案,但似乎没有任何工作可将其序列化为POJO。

我已经尝试过类似的事情

for (Object o : map.keySet()) {
            String key = (String) o;
            System.out.println(key);
            Map<String, JsonElement> value = (Map<String, JsonElement>) map.get(key);
            System.out.println(value); //prints {Updated=week, Time=12pm} for first
            Pump pump = new Pump(value.get("name").toString(), value.get("value").toString(),  value.get("pin").getAsInt());
            arrayList.add(pump);

以下是我的泵类

public class Pump {
    @JsonProperty("name")
    public String name;
    @JsonProperty("pin")
    public int pin;
    @JsonProperty("value")
    public String value;

    public Pump(String name, String value, int pin) {
        this.name = name;
        this.value = value;
        this.pin = pin;
    }

}

任何人都知道如何将该字符串序列化为pojo的?

1 个答案:

答案 0 :(得分:1)

在上面关于gson的评论之后,我找到了解决问题的方法

ArrayList<Pump> pumps = new ArrayList<>();
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, Pump>>(){}.getType();
Map<String, Pump> result = gson.fromJson(jsonString, mapType);

for(Map.Entry<String, Pump> entry : result.entrySet()){
    System.out.println(entry.getValue().name);
    Pump pump = new Pump(entry.getValue().name, entry.getValue().value, entr.getValue().pin);
    pumps.add(pump);
}