目录
前言
在Java中,JsonObject 通常是 javax.json 或 com.google.gson 等库中的类。本文以 Gson 库(com.google.gson)为例,因为它广泛使用且易于操作。
在 Gson 中,以下类型可以转换为 JsonObject:
- JSON 字符串(合法的 JSON 格式);
- Map<String, Object>;
- Java 对象(POJO);
- 嵌套的 JsonElement(如 JsonArray、JsonPrimitive)。
一、引入依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
二、JSON 字符串 转 JsonObject
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"Alice\",\"age\":30,\"city\":\"Beijing\"}";
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject);
}
}
三、Map<String, Object> 转 JsonObject
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.Map;
public class MapToJson {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "Bob");
map.put("age", 25);
map.put("isStudent", false);
Gson gson = new Gson();
JsonObject jsonObject = gson.toJsonTree(map).getAsJsonObject();
System.out.println(jsonObject);
}
}
四、Java 对象(POJO)转 JsonObject
import com.google.gson.Gson;
import com.google.gson.JsonObject;
class Person {
private String name;
private int age;
private String email;
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getters and Setters (可选,Gson 可访问私有字段)
}
public class PojoToJson {
public static void main(String[] args) {
Person person = new Person("Charlie", 35, "charlie@example.com");
Gson gson = new Gson();
JsonObject jsonObject = gson.toJsonTree(person).getAsJsonObject();
System.out.println(jsonObject);
}
}
五、从空对象创建并手动添加字段
import com.google.gson.JsonObject;
public class EmptyJson {
public static void main(String[] args) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "David");
jsonObject.addProperty("age", 28);
jsonObject.addProperty("active", true);
System.out.println(jsonObject);
}
}
六、从 JsonArray 构建 JsonObject
import com.google.gson.*;
public class ArrayToJsonObject {
public static void main(String[] args) {
JsonArray hobbies = new JsonArray();
hobbies.add("reading");
hobbies.add("swimming");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "Eve");
jsonObject.add("hobbies", hobbies);
System.out.println(jsonObject);
}
}
七、总结
| 源类型 | 转换方式 |
|---|---|
| JSON 字符串 | JsonParser.parseString(…).getAsJsonObject() |
| Map | gson.toJsonTree(map).getAsJsonObject() |
| POJO | gson.toJsonTree(pojo).getAsJsonObject() |
| 手动构建 | new JsonObject() + addProperty / add |

4483

被折叠的 条评论
为什么被折叠?



