如何使用 GSON 解析 JSON 字符串?
How to parse JSON string using GSON?
我有一个 JSON 对象,其中包含其他键值类型的字符串。下面是我的 JSON 代码:
{
"objs": [
{
"obj1": {
"ID1": 1,
"ID2": 2
}
}
]
}
如何解析 "ID1"
和 "ID2"
?
JSON 的正确方法是:
{"objs":[
{"obj1":
{"ID1":1,"ID2":2}
}
]
}
如果你想使用 GSON:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("objs");
JsonArray jarray = jobject.getAsJsonArray("obj1");
jobject = jarray.get(0).getAsJsonObject();
String ID1 = jobject.get("ID1").toString();
String ID2 = jobject.get("ID2").toString();
创建 类,添加变量并标记它们以进行反序列化:
public class Root {
@SerializedName("objs")
public List<Obj> objects;
}
public class Obj {
@SerializedName("obj1")
public Obj1 obj1;
}
public class Obj1 {
@SerializedName("ID1")
public int ID1;
@SerializedName("ID2")
public int ID2;
}
然后反序列化你的 JSON:
Gson gson = new Gson();
Root root = gson.fromJson(jsonString, Root.class);
我有一个 JSON 对象,其中包含其他键值类型的字符串。下面是我的 JSON 代码:
{
"objs": [
{
"obj1": {
"ID1": 1,
"ID2": 2
}
}
]
}
如何解析 "ID1"
和 "ID2"
?
JSON 的正确方法是:
{"objs":[
{"obj1":
{"ID1":1,"ID2":2}
}
]
}
如果你想使用 GSON:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("objs");
JsonArray jarray = jobject.getAsJsonArray("obj1");
jobject = jarray.get(0).getAsJsonObject();
String ID1 = jobject.get("ID1").toString();
String ID2 = jobject.get("ID2").toString();
创建 类,添加变量并标记它们以进行反序列化:
public class Root {
@SerializedName("objs")
public List<Obj> objects;
}
public class Obj {
@SerializedName("obj1")
public Obj1 obj1;
}
public class Obj1 {
@SerializedName("ID1")
public int ID1;
@SerializedName("ID2")
public int ID2;
}
然后反序列化你的 JSON:
Gson gson = new Gson();
Root root = gson.fromJson(jsonString, Root.class);