[英]Parsing 2D array in JSON using Java
I have a json file with the following format. 我有以下格式的json文件。 I'm having trouble with parsing the "Locations" segment which value is a
double[][]
array. 我在解析值为“
double[][]
数组”的“位置”段时遇到了麻烦。 What is the best way to parse it? 解析它的最佳方法是什么? Also, I can't figure out how to read the file, I used
json.simple
but it requires to cast every JSONObject
or JSONArray
, which is a bit uncomfortable to use. 另外,我不知道如何读取文件,我使用了
json.simple
但是它需要转换每个JSONObject
或JSONArray
,使用起来有点不舒服。
[
{
"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"]
}
]
Using Gson you can simplify parsing the double[][]
array as 使用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));
}
Output : 输出:
[37.78522, -122.404378]
[37.786661, -122.404571]
[37.786356, -122.408992]
You can parse the object without using any JSON library by creating your own custom functions. 您可以通过创建自己的自定义函数来解析对象,而无需使用任何JSON库。 For instance :
例如 :
function getSpecificLocation(object, index, x, y){
return object[index].Locations[x][y]
}
You can retrieve the Location (0,1) of the 3rd element with : 您可以使用检索第三个元素的位置(0,1):
getSpecificLocation(t,0,0,1)
where t is your JSON object 其中t是您的JSON对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.