我正在使用org.json
来查找json对象和值(org.json
是必需的),并且我正在尝试访问子数组元素。
我的json:
{
"Info": {
"name": "my_json",
},
"my_array": {
"arrays": [
{
"array 1": [
{
"name": "red",
"server": "red1",
"capacity": "123"
},
{
"name": "blue",
"server": "blue1",
"capacity": "456"
}
]
},
{
"array 2": [
{
"name": "white",
"server": "white1",
"capacity": "1234"
},
{
"name": "black",
"server": "black1",
"capacity": "4567"
}
]
}
]
}
}
输出:
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
该方法如下:
public static String processJson(String[] args) throws JSONException {
String value = "";
String jsonData = readFile(args[0]);
JSONObject jobj = new JSONObject(jsonData);
if (args[1].equals("my_array")) {
JSONObject parent = jobj.getJSONObject("my_array");
JSONArray jarr = parent.getJSONArray("arrays");
for (int i = 0; i < jarr.length(); i++) {
for (int j = 0; j < jarr.length(); j++) {
JSONObject test1 = jarr.getJSONObject(j);
System.out.println(test1);
}
}
}
return value;
}
我希望返回值为:
[{"name":"red","capacity":"123","server":"red1"
{"capacity":"456","name":"blue","name":"blue1"}]
是否可以获得array 1
元素?
我认为嵌套循环会处理它,但它只输出相同的时间。
答案 0 :(得分:2)
如果您只想要第一个元素,那么您不需要循环
JSONObject test1 = jarr.getJSONObject(0);
System.out.println(test1);
如果您想格式化test1
您的
System.out.println (test1.toString ().replace ("{\"array 1\":", ""));