您好我正在尝试从Java代码中的Json访问数据,我编写了java代码,同时尝试访问" tittle"或"价值"在json,我只得到一个" title"即事件1,当我试图访问"值"使用列表我得到像[{"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();
}
}
请帮帮我..
答案 0 :(得分:0)
尝试使用此代码
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();
}
}