当JSON没有变量名时,使用gson进行反序列化

时间:2013-08-08 02:06:16

标签: java json gson

我有一个Json吼叫:

{
    "0001":[111, "BLABLA", "LALA", "KKK",80,20],
    "002":[222, "BLABLA", "LALA", "KKK",80,40],
    "003":[333, "BLABLA", "LALA", "KKK",100,20],
    "000":[444, "BLABLA", "LALA", "KKK",800,60],
    "555":[555, "BLABLA", "LALA", "KKK",80,20,
    "100":[48, "BLABLA", "LALA", "KKK",80,20]
}

我在Gson反序列化方面遇到了麻烦。我知道与Json合作的变量名称定义如下:

{
   "item":"001":["id":1,"description":"bla bla"],
   "item":"002":["id":2,"description":"bla bla"]
}

然后我使用相同的json变量名定义了类并执行了解析

public class DataClass
{
  String item;
  int id;
  String description;

  getters and setters;

}

gson.fromJson (json, DataClass.class);

但我不知道怎么做以防万一我需要使用没有变量名的json(在帖子的开头)。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

本课程回答了您的问题:

package stackoverflow.questions.q18116805;

import java.lang.reflect.Type;
import java.util.*;

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

public class Q18116805 {


    public static void main(String[] args) {
        String json =                                                 
            "{  \"0001\":[111, \"BLABLA\", \"LALA\", \"KKK\",80,20],   "+
            "    \"002\":[222, \"BLABLA\", \"LALA\", \"KKK\",80,40],   "+
            "    \"003\":[333, \"BLABLA\", \"LALA\", \"KKK\",100,20],  "+
            "    \"000\":[444, \"BLABLA\", \"LALA\", \"KKK\",800,60],  "+
            "    \"555\":[555, \"BLABLA\", \"LALA\", \"KKK\",80,20],   "+
            "    \"100\":[48, \"BLABLA\", \"LALA\", \"KKK\",80,20]}";

        Type aType = new TypeToken<Map<String,ArrayList<Object>>>() {}.getType();
        Map<String,ArrayList<Object>> map = new Gson().fromJson(json, aType);

        System.out.println(map);
    }
}

结果如下:

  

{0001 = [111.0,BLABLA,LALA,KKK,80.0,20.0],002 = [222.0,BLABLA,   LALA,KKK,80.0,40.0],003 = [333.0,BLABLA,LALA,KKK,100.0,20.0],   000 = [444.0,BLABLA,LALA,KKK,800.0,60.0],555 = [555.0,BLABLA,LALA,   KKK,80.0,20.0],100 = [48.0,BLABLA,LALA,KKK,80.0,20.0]}

答案 1 :(得分:0)

您只需在字符串中添加变量名称即可。在反序列化之前"\"name\":" + json