您JSON
嵌套Objects
在一个中,Array
因此您可以尝试如下所示读取温度值。我用多个温度值更新了你JSON
的值,以便更清楚。
更新的 JSON:
{
"list": [
{
"station": {
"identity": {
"station_name": "station1"
}
},
"obs": {
"temp": {
"temprature": 13.2
}
}
},
{
"station": {
"identity": {
"station_name": "station2"
}
},
"obs": {
"temp": {
"temprature": 15.2
}
}
}
]
}
Code#1:你可以JsonPath
用来读取数据。JsonPath
是使用 XPath 轻松从对象文档中获取值的替代方法。
File jsonFile = new File("Sample.json");
JSONArray jsonArray = new JSONArray(JsonPath.parse(jsonFile).read("list").toString());
for (int i = 0; i < jsonArray.length(); i++) {
String stationName = JsonPath.parse(jsonFile).read("list[" + i + "].station.identity.station_name")
.toString();
if (stationName.equalsIgnoreCase("station2")) {
String temparature = JsonPath.parse(jsonFile).read("list[" + i + "].obs.temp.temprature").toString();
System.out.println("Temparature: "+temparature);
}
}
输出:
Temparature: 15.2
Maven 依赖项JsonPath
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.9.0</version>
</dependency>
下面的代码片段可用于在没有任何库的情况下读取数据。
代码#2:读取所有温度值。
String jsonDataAsString = new String(Files.readAllBytes(Paths.get("Sample.json")));
JSONObject jsonObject = new JSONObject(jsonDataAsString);
JSONArray jsonArray = new JSONArray(jsonObject.get("list").toString());
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = new JSONObject(jsonArray.get(i).toString());
jsonObject = new JSONObject(jsonObject.get("obs").toString());
jsonObject = new JSONObject(jsonObject.get("temp").toString());
System.out.println("Temparature" + i + ": " + jsonObject.get("temprature"));
}
输出:
Temparature0: 13.2
Temparature1: 15.2
代码#3:根据站名获取温度值。
String jsonDataAsString = new String(Files.readAllBytes(Paths.get("Sample.json")));
JSONObject jsonTemparatureObject;
JSONObject jsonObject = new JSONObject(jsonDataAsString);
JSONArray jsonArray = new JSONArray(jsonObject.get("list").toString());
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = new JSONObject(jsonArray.get(i).toString());
jsonTemparatureObject = new JSONObject(jsonObject.get("obs").toString());
jsonObject = new JSONObject(jsonObject.get("station").toString());
jsonObject = new JSONObject(jsonObject.get("identity").toString());
if (jsonObject.get("station_name").toString().equalsIgnoreCase("station2")) {
jsonObject = new JSONObject(jsonTemparatureObject.get("temp").toString());
System.out.println("Temparature: " + jsonObject.get("temprature"));
}
}
输出:
Temparature: 15.2