gpt4 book ai didi

java - java中访问多个json对象

转载 作者:太空宇宙 更新时间:2023-11-04 13:43:25 25 4
gpt4 key购买 nike

我正在尝试使用Java代码访问Json中的数据,我已经编写了Java代码,在尝试访问json中的“tittle”或“value”时,我只获得了“title”的一个值,即事件1,当我尝试使用列表访问“values”时,我得到了诸如[{"0":"1_a","1":"1_b"}, {"0":"2_a","1":"2_b"}]之类的数据

我想访问“标题”和“值”的数据,即事件 2 也应该显示。全部进口已完成。代码在这里

 public class JsonToJava {

public void JsontoString() {

String title;
String jsonString = "{\"title\":\"Event 1\","
+ "\"param\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"],"
+ "\"status\":true,"
+ "\"values\":[{"
+ "\"0\":{\"0\":\"1_a\",\"1\":\"1_b\"},"
+ "\"1\":{\"0\":\"2_a\",\"1\":\"2_b\"}}]"
+ ",\"$$hashKey\":\"object:3\"}"
+ ",{\"title\":\"Event 2\","
+ "\"param\":[\"1\",\"2\",\"3\",\"4\",\"Price1\",\"Price2\",\"5\",\"Status\"],"
+ "\"status\":true," + "\"values\":[{"
+ "\"0\":{\"0\":\"A_a\",\"1\":\"A_b\"},"
+ "\"1\":{\"0\":\"B_a\",\"1\":\"B_b\"}}]"
+ ",\"$$hashKey\":\"object:4\"}";

try {
title = new JSONObject(jsonString).getString("title");

System.out.println(title);

// JSONObject obj = new
// JSONObject("{"0":{"0":"1_a","1":"1_b"},"1":{"0":"2_a","1":"2_b"}}");

JSONObject obj1 = new JSONObject(jsonString);

List<String> list = new ArrayList<String>();
JSONArray array = obj1.getJSONArray("values");

String val = array.getString(0);

for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i).getString("0"));
list.add(array.getJSONObject(i).getString("1"));
}

System.out.println(list);

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void main(String[] args) {
// TODO Auto-generated method stub

JsonToJava js = new JsonToJava();

js.JsontoString();
}
}

最佳答案

尝试使用此代码

public void JsontoString() {
String jsonString = "{\"root\":[{\"title\":\"Event 1\"," + "\"param\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]," + "\"status\":true," + "\"values\":[{"
+ "\"0\":{\"0\":\"1_a\",\"1\":\"1_b\"}," + "\"1\":{\"0\":\"2_a\",\"1\":\"2_b\"}}]" + ",\"$$hashKey\":\"object:3\"}"
+ ",{\"title\":\"Event 2\"," + "\"param\":[\"1\",\"2\",\"3\",\"4\",\"Price1\",\"Price2\",\"5\",\"Status\"]," + "\"status\":true,"
+ "\"values\":[{" + "\"0\":{\"0\":\"A_a\",\"1\":\"A_b\"}," + "\"1\":{\"0\":\"B_a\",\"1\":\"B_b\"}}]" + ",\"$$hashKey\":\"object:4\"}]}";
try {
System.out.println(jsonString);
JSONObject obj1 = new JSONObject(jsonString);

List<String> list = new ArrayList<String>();
JSONArray array = obj1.getJSONArray("root");
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i).getString("title"));
}
System.out.println(list);
} catch (JSONException e) {
e.printStackTrace();
}
}

关于java - java中访问多个json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31079592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com