|
java Object转JSONObject在Java中将对象(Object)转换为JSONObject可以使用第三方库如Gson或Jackson。
- import com.google.gson.Gson;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonParser;
- import org.json.JSONObject;
-
- public class Main {
- public static void main(String[] args) {
- // 创建要转换的对象
- MyObject myObj = new MyObject("John", "Doe");
-
- // 使用Gson将对象转换为JSON字符串
- Gson gson = new Gson();
- String jsonStr = gson.toJson(myObj);
-
- // 使用JsonParser将JSON字符串解析成JsonElement
- JsonParser parser = new JsonParser();
- JsonElement element = parser.parse(jsonStr);
-
- // 使用getAsJsonObject()方法获取JsonObject
- JSONObject jsonObject = (JSONObject) element;
-
- System.out.println(jsonObject.toString());
- }
- }
-
- class MyObject {
- private String firstName;
- private String lastName;
-
- public MyObject(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- // Getters and setters...
- }<span style="background-color: rgb(255, 255, 255); color: rgb(51, 51, 51); font-family: -apple-system, Arial, Helvetica, sans-serif;">输出结果:</span>
复制代码
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.json.JSONObject;
-
- public class Main {
- public static void main(String[] args) throws Exception {
- // 创建要转换的对象
- MyObject myObj = new MyObject("John", "Doe");
-
- // 使用ObjectMapper将对象转换为JSON字符串
- ObjectMapper objectMapper = new ObjectMapper();
- String jsonStr = objectMapper.writeValueAsString(myObj);
-
- // 使用org.json包中的JSONTokener类将JSON字符串解析成JSONObject
- JSONObject jsonObject = new JSONObject(new org.json.JSONTokener(jsonStr));
-
- System.out.println(jsonObject.toString());
- }
- }
-
- class MyObject {
- private String firstName;
- private String lastName;
-
- public MyObject(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- // Getters and setters...
- }
复制代码 输出结果与上述相同:
- {"firstName":"John","lastName":"Doe"}
复制代码
|
|
|