java字符串转json 并取json值
时间: 2023-11-08 11:52:42 浏览: 90
要将Java字符串转换为JSON并获取JSON值,你可以使用JSON库,如Jackson或Gson。以下是一个示例代码,演示如何完成此操作:
使用Jackson库:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class Main {
public static void main(String[] args) {
try {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
// 将JSON字符串转换为JsonNode对象
JsonNode jsonNode = objectMapper.readTree(jsonString);
// 从JsonNode中获取特定字段的值
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
String city = jsonNode.get("city").asText();
// 打印结果
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
使用Gson库:
```java
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main {
public static void main(String[] args) {
try {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 创建JsonParser对象
JsonParser parser = new JsonParser();
// 将JSON字符串解析为JsonObject
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
// 从JsonObject中获取特定字段的值
String name = jsonObject.get("name").getAsString(); int age = jsonObject.get("age").getAsInt();
String city = jsonObject.get("city").getAsString();
// 打印结果
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文