从java中嵌套的JSON格式文件中读取值

时间:2015-09-03 04:18:52

标签: java json

我不确定如何阅读以下JSON文件,因为嵌套数组没有映射到它的键。我知道使用JSONArray fileList = (JSONArray) jsonObject.get(fileName);允许我访问第一个数组但是从这里开始我就卡住了。

{
"file1_1.txt": [
   [
     "2015-08-26 12:03:44 +1200",
     "d6072668c069d40c27c3f982789b32e33f23575316ebbbc11359c49929ac8adc"
   ],
   [
     "2015-08-26 12:03:42 +1200",
     "a2ebea1d55e6059dfb7b8e8354e0233d501da9d968ad3686c49d6a443b9520a8"
   ]
 ],
"file1_2.txt": [
   [
     "2015-08-26 12:03:42 +1200",
     "c62b8de531b861db068eac1129c2e3105ab337b225339420d2627c123c7eae04"
   ]
 ],
"file2_1.txt": [
   [
     "2015-08-26 12:03:42 +1200",
     "3032e7474e22dd6f35c618045299165b0b42a9852576b7df52c1b22e3255b112"
   ]
 ]
}

2 个答案:

答案 0 :(得分:1)

JSONArray fileList = (JSONArray) jsonObject.get(fileName);
JSONArray inner = fileList.getJsonArray(0);

您可以使用inner.size();

获取元素数量

PS:我在jsonlint.com上复制并粘贴了JSON示例,它显示为有效的JSON格式。

答案 1 :(得分:0)

您可以JSONObject格式使用json。使用JSONObject,您可以获取JSONObject例如:file1_1.txt, file1_2.txt, etc..

的密钥

找到以下代码:

String str = " { "+
        "\"file1_1.txt\": ["+
           "["+
             "\"2015-08-26 12:03:44 +1200\","+
             "\"d6072668c069d40c27c3f982789b32e33f23575316ebbbc11359c49929ac8adc\""+
           "],"+
           "["+
             "\"2015-08-26 12:03:42 +1200\","+
             "\"a2ebea1d55e6059dfb7b8e8354e0233d501da9d968ad3686c49d6a443b9520a8\""+
           "]"+
     "],"+
        "\"file1_2.txt\": ["+
           "["+
             "\"2015-08-26 12:03:42 +1200\","+
             "\"c62b8de531b861db068eac1129c2e3105ab337b225339420d2627c123c7eae04\""+
           "]"+
         "],"+
        "\"file2_1.txt\": ["+
           "["+
            "\"2015-08-26 12:03:42 +1200\","+
           " \"3032e7474e22dd6f35c618045299165b0b42a9852576b7df52c1b22e3255b112\""+
          " ]"+
         "]"+
        "}";


    JSONObject obj = new JSONObject(str);

    Set<String> set = obj.keySet(); 

    System.out.println(set);

这里我将您的格式String str传递给'JSONObject'并创建实例obj。通过使用obj我通过调用obj.keySet()来获取json密钥它将返回Set实例,就像keySet()方法那样另一种方法,即'keys',返回Iterator个实例。

试一试:)