{ "subFocus": "", "opration": "", "postResult": "success", "extras": null, "focus": "map", "intent": "poiSearch", "operation": "", "object": { "keyword": "加油站", "district": { "nearby": "", "city": "西安" }, "api": "searchInCity", "limit": "true" }, "playMode": "" } 获取district中的city,怎么写?用java
时间: 2023-07-24 15:14:01 浏览: 124
你可以使用Java中的JSON解析库来解析JSON字符串,并获取`district`中的`city`值。以下是一个示例代码:
```java
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"subFocus\":\"\",\"opration\":\"\",\"postResult\":\"success\",\"extras\":null,\"focus\":\"map\",\"intent\":\"poiSearch\",\"operation\":\"\",\"object\":{\"keyword\":\"加油站\",\"district\":{\"nearby\":\"\",\"city\":\"西安\"},\"api\":\"searchInCity\",\"limit\":\"true\"},\"playMode\":\"\"}";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject districtObject = jsonObject.getJSONObject("object").getJSONObject("district");
String city = districtObject.getString("city");
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用了JSON解析库`org.json.JSONObject`,首先将JSON字符串转换为一个`JSONObject`对象。然后,我们通过连续调用`getJSONObject()`方法,从外层到内层逐层获取嵌套的JSONObject对象。最后,通过调用`getString()`方法,获取`district`中的`city`值。
请注意,你需要根据你的实际情况调整JSON字符串的解析代码。确保包含了正确的JSON键名和嵌套结构。
阅读全文