如何在Java中访问JSON层次结构
以下JSON来自一个名为response的StringBuffer变量中的服务器,在将其设置为toString()后,我可以在输出中看到它 到目前为止,我编写的代码无法解决我的目的:如何在Java中访问JSON层次结构,java,json,Java,Json,以下JSON来自一个名为response的StringBuffer变量中的服务器,在将其设置为toString()后,我可以在输出中看到它 到目前为止,我编写的代码无法解决我的目的: JSONArray ar=new JSONArray(response. JSONObject jObject = ar.getJSONObject(0); JSONObject jObject = ar.getJSONObject(1); String JObjectString=jObject.toString
JSONArray ar=new JSONArray(response.
JSONObject jObject = ar.getJSONObject(0);
JSONObject jObject = ar.getJSONObject(1);
String JObjectString=jObject.toString();
System.out.println("The JObject String "+JObjectString);
我需要存储每个元素,包括“脉冲和颗粒”、“DAL”、“Tea”、“A3大小的纸张”等,并将该数组中的每个元素存储在字符串变量中。
由于层次结构中的每个元素都太嵌套了,我如何访问它呢?由于JSONObject实现了映射接口,您可以使用方法列出它的所有字段名和值
jObject.entrySet()
如果您事先知道字段的名称,则可以按名称检索它们:
JSONArray categories = jObject.get("Categories");
但我建议使用一些不错的JSON库,比如google的Gson,这样您就可以定义数据类,然后自动将JSON解析为类的层次结构:
class Element {
String _id;
List<Category> categories;
public Element(){}
}
class Category {
private List<Entry> entries;
public Category (){}
}
class Entry {
private List<String> units;
public Entry (){}
}
由于JSONObject实现了映射接口,所以可以使用方法列出它的所有字段名和值
jObject.entrySet()
如果您事先知道字段的名称,则可以按名称检索它们:
JSONArray categories = jObject.get("Categories");
但我建议使用一些不错的JSON库,比如google的Gson,这样您就可以定义数据类,然后自动将JSON解析为类的层次结构:
class Element {
String _id;
List<Category> categories;
public Element(){}
}
class Category {
private List<Entry> entries;
public Category (){}
}
class Entry {
private List<String> units;
public Entry (){}
}