java解析json字符串
时间: 2023-07-19 18:28:33 浏览: 84
java解析任意层数json字符串的方法
5星 · 资源好评率100%
在Java中解析JSON字符串可以使用Java自带的org.json库或者第三方库如Jackson、Gson等。
使用org.json库解析JSON字符串的示例代码:
```java
import org.json.*;
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
```
使用Jackson库解析JSON字符串的示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>(){});
String name = (String) jsonMap.get("name");
int age = (int) jsonMap.get("age");
String city = (String) jsonMap.get("city");
```
使用Gson库解析JSON字符串的示例代码:
```java
import com.google.gson.*;
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
Gson gson = new Gson();
Map<String, Object> jsonMap = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>(){}.getType());
String name = (String) jsonMap.get("name");
int age = (int) jsonMap.get("age");
String city = (String) jsonMap.get("city");
```
阅读全文