使用Java在JSON中解析2D数组

时间:2015-03-16 15:45:24

标签: java json

我有一个json文件,格式如下。 我在解析&#34;地点&#34;时遇到了问题。段的值是double[][]数组。 解析它的最佳方法是什么? 此外,我无法弄清楚如何阅读文件,我使用了json.simple,但它需要投射每个JSONObjectJSONArray,这有点让人不舒服。< / p>

[
  {
    "ID": 123456,
    "Locations": [
      [37.785220, -122.404378], 
      [37.786661, -122.404571],
      [37.786356, -122.408992]
      ],
      "Time": 1426510324,
      "Tests Failed" : ["T1", "T2", "T5"]
  },
  {
    "ID": 123456,
    "Locations": [
      [37.793450, -122.422616], 
      [37.782869, -122.462613],
      [37.772964, -122.458579],
      [37.762787, -122.458922]
      ],
      "Time": 1426510325,
      "Tests Failed" : ["T3", "T5", "T6"]
  },
  {
    "ID": 123456,
    "Locations": [
      [37.778689, -122.514214], 
      [37.782759, -122.511639],
      [37.805187, -122.468924],
      [37.771611, -122.468666],
      [37.759059, -122.457336]
      ],
      "Time": 1426511324,
      "Tests Failed" : ["T1", "T5", "T7"]
  }
]

2 个答案:

答案 0 :(得分:0)

使用Gson,您可以简化double[][]数组的解析

String input = "[\r\n" + 
        "  {\r\n" + 
        "    \"ID\": 123456,\r\n" + 
        "    \"Locations\": [\r\n" + 
        "      [37.785220, -122.404378], \r\n" + 
        "      [37.786661, -122.404571],\r\n" + 
        "      [37.786356, -122.408992]\r\n" + 
        "      ],\r\n" + 
        "      \"Time\": 1426510324,\r\n" + 
        "      \"Tests Failed\" : [\"T1\", \"T2\", \"T5\"]\r\n" + 
        "  }]";

// Parse the input as an array
JSONArray jArr = new JSONArray(input);

// Get the required Location object
JSONObject jObj1 = jArr.getJSONObject(0);

// Get the Locations
String locations = jObj1.getJSONArray("Locations").toString();

// Parse using Gson
double[][] dArr = new Gson().fromJson(locations, double[][].class);

// Print the array
for (double[] d : dArr) {
    System.out.println(Arrays.toString(d));
}

输出:

[37.78522, -122.404378]
[37.786661, -122.404571]
[37.786356, -122.408992]

答案 1 :(得分:0)

您可以通过创建自己的自定义函数来解析对象而无需使用任何JSON库。例如:

function getSpecificLocation(object, index, x, y){
    return object[index].Locations[x][y]
}

您可以使用以下方法检索第3个元素的位置(0,1):

getSpecificLocation(t,0,0,1)

其中t是您的JSON对象