温馨提示×

java json字符串怎么转json对象

小亿
115
2023-09-27 11:27:13
栏目: 编程语言

可以使用Java的JSON库来将JSON字符串转换为JSON对象。常用的JSON库有GSON、Jackson、Fastjson等。以下是使用GSON库将JSON字符串转换为JSON对象的示例代码:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 使用JsonParser将JSON字符串转换为JSON对象
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
// 输出JSON对象的属性值
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);
}
}

在上面的示例中,我们首先创建一个JsonParser对象,然后使用它的parse()方法将JSON字符串转换为JsonElement对象,再使用getAsJsonObject()方法将JsonElement对象转换为JsonObject对象。最后,可以使用JsonObject对象的get()方法获取JSON对象的属性值。

0