2017-08-02 55 views
1

我使用org.json来查找json对象和值(需要org.json),并且我试图访问子数组元素。在Java中获取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

什么是ARGS [1]? – jeanr

+0

@jeanr我想这是'my_array' –

+0

当我尝试读取json有效载荷的结构时,它看起来像这样:my_array.arrays [0]。“array 1” my_array.arrays [1]。“array 1” 你确定你的json格式排列整齐,即在一个适当的层次或关系? – dirai

回答

2

如果你只想要第一个元素,然后如果你想格式化test1你可以不需要一个循环

 JSONObject test1 = jarr.getJSONObject(0); 
     System.out.println(test1); 

System.out.println (test1.toString().replace ("{\"array 1\":", "")); 
+0

不错!删除了两个循环! –

+0

如果将'array 1'作为参数传递,您将如何移除它?例如,'replace(“{\”variable name \“:”,“”)'不会删除字符串。 –

+0

你可以使用像'str.replace(var,“”)''这样的变量,其中'var'是一个类似于'var =“{\”“+”array 1“+”\“:”;';'' –