![](/img/trans.png)
[英]Need to parse the JSON ARRAYS that are inside the JSON Object in JAVA
[英]need to read the json arrays inside the object using java
我正在尝试使用 java 读取 JSON,但无法做到这一点。 所以需要编写一个java代码来读取对象内部数组的JSON文件。
"exclusion":{
"serviceLevelList":[ "SIS98", "C4P","SNTP" ],
"pid":[ "ABC", "DEF" ]
}
将 JSONObject 用于简单的 JSON,将 JSONArray 用于 JSON 数组。
try {
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("/config.json"));//path to the JSON file.
JSONObject jsonObject = data.getJSONObject("exclusion");
JSONArray array= jsonObject.getJSONArray("pid");
} catch (Exception e) {
e.printStackTrace();
}
使用谷歌简单库
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>
尝试这个:
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
JSONObject exclusion= json.getJSONObject("exclusion");
String serviceLevelList[]= pilot.getString("serviceLevelList");
String pid[]= pilot.getString("pid");
您可以尝试Gson 对象的方法将 JSON 转换为 Java 对象和 Vise Versa。
因为你可以使用依赖如下
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
Gson 对象提供了如下几种方法:
Gson gson = new Gson();
// Convert Java object to JSON and assign to a String
String jsonInString = gson.toJson(obj);
//Convert JSON to Java object, read it from a JSON String.
String jsonInString = "{'name' : 'myname'}";
Staff staff = gson.fromJson(jsonInString, Student.class);
你可以用你的代码试试这个:-)
我们多年来一直在使用 XStream。 虽然我们主要用于 .XML 文件,但它也支持读取和写入 JSON,我们已经多次使用这种方式。
使用此依赖项片段将其包含在您的 Maven 项目中:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11</version>
</dependency>
你在他们的网站上有你需要的所有信息。 他们甚至有一个“两分钟教程”和一个可能有用的“ JSON 教程”(顺便说一下,其中提到了“从 JSON 读取”可能直接适用于您的情况)。 互联网上还有一些帖子,正如他们在参考部分中所记录的那样,甚至还有 StudyTrails 中的XStream 课程。
通过使用 JSONObject 和 JSONArray 类,您可以对 json 数据执行不同的操作。
有关处理不同格式的 json 数据的信息,请参阅此链接,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.