json相关知识

1、JSONObject转换为自定义的类 (前提:两者的字段一致),字符串转换为自定义的类

fastjson中:

1)jsonobject转为自定义的类

// 创建一个 JSONObject 对象

JSONObject jsonObject = new JSONObject();

jsonObject.put("name", "Alice"); jsonObject.put("age", 25);

// 将 JSONObject 转换为 Person 对象

Person person = JSON.parseObject(jsonObject, Person.class);

2)或者将JSONObject 先转为字符串,再转为Person对象

    字符串转换为自定义的类

String jsonString = "{\"name\":\"John\",\"age\":30}";
// 使用Fastjson将JSON字符串转换为Person对象
Person person = JSON.parseObject(jsonString, Person.class);

org.json中:字符串转换为自定义的类也是用这种方式

方式一:使用 Jackson 库

ObjectMapper objectMapper = new ObjectMapper();

PsgData psgData = objectMapper.readValue(jsonObject.toString(), PsgData.class);

方式二:手动转

// 创建一个 JSONObject 对象

JSONObject jsonObject = new JSONObject();

jsonObject.put("name", "Alice");

jsonObject.put("age", 25);

// 创建 PsgData 对象

PsgData psgData = new PsgData();

// 手动赋值

psgData.setName(jsonObject.getString("name"));

psgData.setAge(jsonObject.getInt("age"));

2、JSONObject转换为String

fastjson中:

String jsonString = jsonObject.toJSONString();

JSON.toJSONString(psgData)

JSONObject.toJSONString(psgData) 

org.json中:

String jsonString = jsonObject.toString();

3、自定义的类对象转换为String

alibaba fastjson:

JSON.toJSONString(psgData)   // 正确的

JSONObject.toJSONString(psgData)  //可能也行,不建议用

org.json:

ObjectMapper objectMapper = new ObjectMapper();

// 将 Person 对象转换为 JSON 字符串

String jsonString = objectMapper.writeValueAsString(person);

4、String转换为JSONObject

(1) alibaba.fastjson:

String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JSONObject jsonObject = JSON.parseObject(jsonString);

(2)org.json:

String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);

5、自定义的类转为jsonobject

(1)fastjson中:

// 将自定义的类对象转换为JSONObject
JSONObject jsonObject = (JSONObject) JSON.toJSON(person);

(2)org.json

JSONObject jsonObject = new JSONObject(person);

 

posted @ 2025-05-15 15:27  coco9821  阅读(21)  评论(0)    收藏  举报