将数组列表中的 JSON 转换为 ArrayList (Java) [英] Convert JSON inside an array list to an ArrayList (Java)
问题描述
我的输出如下所示:
<代码>{问题字段1":{"id":"customfield_10561","name":"错误免责声明",类型":空,"值":"..."},问题字段2":{"id":"customfield_13850","name":"ENV 工作类型 (DT)",类型":空,值":空},...问题字段9":{"id":"timespent","name":"花费的时间","类型":"空",值":空"}}
我想创建一个 ArrayList 并在其中添加所有名称(如果该值不为空).知道我应该如何在 Java 中执行此操作吗?
假设您有以下 json 对象:
<代码>{"name":"约翰·多伊",年龄":100,"job":"科学家","地址":["地址 1","地址 2","地址 3"]}
要获取对象内部的不同字段,请创建一个 JSONParser 对象并使用 get()
方法获取该字段中保存的值
试试 {FileReader reader = new FileReader("/path/to/file.json");JSONParser jsonParser = new JSONParser();JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);String name = (String) jsonObject.get("name");System.out.println("名称为" + 名称);long age = (long) jsonObject.get("age");System.out.println("年龄为:" + age);JSONArray lang = (JSONArray) jsonObject.get("addresses");for (int i = 0; i < lang.size(); i++) {System.out.println("地址" + (i + 1) + ":" + lang.get(i));}} catch (FileNotFoundException fileNotFound) {fileNotFound.printStackTrace();} 捕捉(IOException io){io.printStackTrace();} catch (NullPointerException npe) {npe.printStackTrace();} catch (org.json.simple.parser.ParseException e) {e.printStackTrace();}}
My output looks like this :
{
"IssueField1":{
"id":"customfield_10561",
"name":"Bug Disclaimer",
"type":null,
"value":"<div style>...</div>"
},
"IssueField2":{
"id":"customfield_13850",
"name":"ENV Work Type (DT)",
"type":null,
"value":null
},
.
.
.
"IssueField9":{
"id":"timespent",
"name":"Time Spent",
"type":"null",
"value":"null"
}
}
I want to create an ArrayList and and add all names in it if the value is not null. Any idea how should I do this in Java ?
Lets say you have the following json object:
{
"name":"john doe",
"age":100,
"job":"scientist",
"addresses":["address 1","address 2","address 3"]
}
to get the different fields inside of the object, create a JSONParser object and use the get()
method to get the value held in that field
try {
FileReader reader = new FileReader("/path/to/file.json");
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
String name = (String) jsonObject.get("name");
System.out.println("The name is " + name);
long age = (long) jsonObject.get("age");
System.out.println("The age is: " + age);
JSONArray lang = (JSONArray) jsonObject.get("addresses");
for (int i = 0; i < lang.size(); i++) {
System.out.println("Address " + (i + 1) + ": " + lang.get(i));
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
这篇关于将数组列表中的 JSON 转换为 ArrayList (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!