我想从JSON获取纬度和经度值,JSON由两个对象“ stoppage”和“ routePlaceback”组成,现在我只能从“ routePlaceback”获取数据,但是我不知道如何只获取经度和纬度的值?代码如下,
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Finder_Json
{
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception
{
// parsing JSON file
Object sampleFile_object = new JSONParser().parse(new FileReader("sample.json"));
// typecasting object to JSONObject
JSONObject sampleFile_JSONObject = (JSONObject) sampleFile_object;
JSONArray routePlaceback = (JSONArray) sampleFile_JSONObject.get("routePlaceback");
Iterator iterator_1 = routePlaceback.iterator();
while (iterator_1.hasNext())
{
System.out.println(iterator_1.next());
System.out.println("\n");
}
}
}
我的sample.json
文件包括,
{
"stoppage":
[
{
"latitude": "23.074207",
"longitude": "72.557227",
"record_date": 1556217000,
"start_time": 1556217000,
"end_time": 1556304360,
"duration_time": 1456
}
],
"routePlaceback":
[
{
"distance": 0.36,
"longitude": "72.502385",
"ignition": 1,
"record_date": 1556303400,
"speed": 53.708,
"latitude": "23.034403"
},
{
"distance": 0.38,
"longitude": "72.506072",
"ignition": 1,
"record_date": 1556303430,
"speed": 25.927999,
"latitude": "23.034045"
}
]
}
这是我运行上述代码时得到的,
但是我想要的输出是
23.034403, 72.502385
23.034045, 72.506072
答案 0 :(得分:0)
您可以在显示时提取所需的值:
import { vm } from 'path/main.js'
答案 1 :(得分:0)
这是您的while循环修改:
while (iterator_1.hasNext()){
JSONObject next = (JSONObject) iterator_1.next();
System.out.print(next.get("latitude") + ", " + next.get("longitude"));
System.out.println("\n");
}
只需获取iterator_1.next()
返回的对象的“纬度”和“经度”属性。
而且System.out.println();
已经打印了新行,System.out.println("\n);
实际上已经打印了两个新行。我不知道这是否是您想要的。
答案 2 :(得分:0)
您正在尝试访问property of an Object
所在的Object
。
while (iterator_1.hasNext())
{
JSONObject k= (JSONObject)iterator_1.next()
System.out.println(k.latitude+" "+k.longitude);
System.out.println("\n");
}
答案 3 :(得分:0)
我稍微修改了您的代码以实现目标。请找到以下示例:
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Finder_Json
{
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception
{
// parsing JSON file
Object sampleFile_object = new JSONParser().parse(new FileReader("src/main/resources/sample.json"));
// typecasting object to JSONObject
JSONObject sampleFile_JSONObject = (JSONObject) sampleFile_object;
JSONArray routePlaceback = (JSONArray) sampleFile_JSONObject.get("routePlaceback");
Iterator iterator = routePlaceback.iterator();
while (iterator.hasNext()) {
JSONObject objt = (JSONObject) iterator.next();
System.out.println(objt.get("latitude") + ", " + objt.get("longitude"));
}
}
}