由Gson解析json

时间:2014-03-09 09:23:10

标签: java json

我的第一个Json格式

{
   object:[
     {
       name: "me",
       age: 20
     }
   ]
}

我的第二个Json格式

{
    object:
    {
      name: "me",
      age: 20
    }
}

所以对象有时是jsonObject,有时候是JsonArray,如何使用gson jar将其转换为Java类对象。

2 个答案:

答案 0 :(得分:0)

考虑到你有两个不同的JSON表示,我会在这里展示每一个。

首先让我们创建一个在两种表示中都很常见的基本结构:

class A {
    public String name,
    public int age,
}

现在是第一个JSON表示:

class B {
    public ArrayList<A> object;
}

// Now getting the object from Gson
Gson gson = new Gson();
B obj = gson.fromJson("you json string", B.class);

并且,这是第二个JSON表示的转换:

class C {
    public A object;
}

// Now getting the object from Gson
Gson gson = new Gson();
C obj = gson.fromJson("you json string", C.class);

答案 1 :(得分:0)

如果您的对象可以是JsonObject或JsonArray,则需要手动处理以解析Json。以下是使用Google的Gson库的代码。

String jsonStr = "your json string ";

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();

JsonElement elem = jsonObj.get("object");

if(elem.isJsonArray()) { // Array
    List<YourClass> notelist = gson.fromJson(elem.toString(), new TypeToken<List<YourClass>>(){}.getType());
} else if(elem.isJsonObject()) { // Object
    YourClass note = gson.fromJson(elem.toString(), YourClass.class);
}

YourClass应该像

class YourClass {
   String name;
   int age;

   //Setters and Getters 
}