1

我有一个 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(在帖子的开头),我不知道该怎么做。任何人都可以帮忙吗?

4

2 回答 2

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]}

于 2013-10-05T22:16:56.477 回答
0

您可以在字符串中添加一个变量名。"\"name\":" + json在反序列化之前。

于 2013-08-08T02:44:29.040 回答