This article lets you use JSONObject and JSONArray proficiently

rely

Import Ali's fastjson dependency.

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

type conversion

Convert between String and JSON

By JSONObject.parseObject(String str)converting the string to a JSONObject object, this method supports JSON strings, and the JSON string format is as follows:

Writing method one:

{
    
    
	"code":"1",
	"status":"success",
	"target":"年入百万",
	"msg":{
    
    
		"seq":"20230424",
		"weather":"晴",
		"salary":9000.00,
		"job":"摆地摊"
	},
	"goods":{
    
    
		"sum":2000.00,
		"manufacturer":{
    
    
			"address":"青口",
			"boss":"张三"
		},
		"details":[
			{
    
    
				"name":"土豆",
				"weight":"500斤"
			},
			{
    
    
				"name":"豆腐",
				"weight":"250斤"
			}
		]
	}
}

Writing method two:

{
    
    "code":"1","status":"success","target":"年入百万","msg":{
    
    "seq":"20230424","weather":"晴","salary":9000.00,"job":"摆地摊"},"goods":{
    
    "sum":2000.00,"manufacturer":{
    
    "address":"青口","boss":"张三"},"details":[{
    
    "name":"土豆","weight":"500斤"},{
    
    "name":"豆腐","weight":"250斤"}]}}

Conversion case code:

        String JSONstr1 = "{\n" +
                "\t\"code\":\"1\",\n" +
                "\t\"status\":\"success\",\n" +
                "\t\"target\":\"年入百万\",\n" +
                "\t\"msg\":{\n" +
                "\t\t\"seq\":\"20230424\",\n" +
                "\t\t\"weather\":\"晴\",\n" +
                "\t\t\"salary\":9000.00,\n" +
                "\t\t\"job\":\"摆地摊\"\n" +
                "\t},\n" +
                "\t\"goods\":{\n" +
                "\t\t\"sum\":2000.00,\n" +
                "\t\t\"manufacturer\":{\n" +
                "\t\t\t\"address\":\"青口\",\n" +
                "\t\t\t\"boss\":\"张三\"\n" +
                "\t\t},\n" +
                "\t\t\"details\":[\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"name\":\"土豆\",\n" +
                "\t\t\t\t\"weight\":\"500斤\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"name\":\"豆腐\",\n" +
                "\t\t\t\t\"weight\":\"250斤\"\n" +
                "\t\t\t}\n" +
                "\t\t]\n" +
                "\t}\n" +
                "}";
        String JSONstr2 = "{\"code\":\"1\",\"status\":\"success\",\"target\":\"年入百万\",\"msg\":{\"seq\":\"20230424\",\"weather\":\"晴\",\"salary\":9000.00,\"job\":\"摆地摊\"},\"goods\":{\"sum\":2000.00,\"manufacturer\":{\"address\":\"青口\",\"boss\":\"张三\"},\"details\":[{\"name\":\"土豆\",\"weight\":\"500斤\"},{\"name\":\"豆腐\",\"weight\":\"250斤\"}]}}";
        JSONObject jsonObject1 = JSONObject.parseObject(JSONstr1);
        JSONObject jsonObject2 = JSONObject.parseObject(JSONstr2);
        System.out.println(jsonObject1);
        System.out.println(jsonObject2);

output:


If it is a string of JSONArray type, as follows:

		"details":[
			{
    
    
				"name":"土豆",
				"weight":"500斤"
			},
			{
    
    
				"name":"豆腐",
				"weight":"250斤"
			}
		]

then you need to useJSONArray.parseArray()


To convert JSON to String, use toJSONString(), as follows:

        JSONObject jsonObject = new JSONObject();
        jsonObject.toJSONString();
        JSONObject.toJSONString(jsonObject);

		JSONArray JSONArray = new JSONArray();
        JSONArray.toJSONString();
        JSONArray.toJSONString(JSONArray);

JSON and entity classes

@Slf4j
public class Test2 {
    
    
    public static void main(String[] args) {
    
    
        String roleStr = "{\"name\":\"张三\",\"age\":7}";
        Role role = JSONObject.parseObject(roleStr, Role.class);
        log.info(role.toString());
        log.info(role.getName());
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Role {
    
    
    private String name;
    private Integer age;

}

JSON and Maps

        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 17);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(map));

Convert between XML and Map

https://blog.csdn.net/y1534414425/article/details/105770851

CRUD

retrieve data

Get JSONObject data:

Get the corresponding value data according to the key value.

        // 获取 target 的值,返回 String
        String target = jsonObject2.getString("target");
        // 获取 code 的值,返回 Object
        Object code = jsonObject2.get("code");
        // 获取 msg 的值,返回 JSONObject
        JSONObject msg = jsonObject2.getJSONObject("msg");
        // 获取 details 的值,返回 JSONArray
        JSONArray jsonArray = jsonObject2.getJSONObject("goods").getJSONArray("details");

Note: When the data to be obtained does not exist in JSONObject and the obtained object is null, NullPointerException will not be reported. If you continue to obtain data for this null object, NullPointerException will be reported.


Get JSONArray data:

Return the object according to the index position, the index subscript starts from 0.

        // 获取索引为 0 处的 JSON 对象,返回 Object
        Object o = jsonArray.get(0);
        // 获取索引为 0 处的 JSON 对象,返回 JSONObject
        JSONObject jsonObject = jsonArray.getJSONObject(0);

Note: If the data to be obtained does not exist in the JSONArray, a null pointer will be reported.

remove data

Delete data in JSONObject:

        // 删除指定的 key ,返回被删除的数据 Object
        Object msg1 = jsonObject1.remove("msg");
        // 当 code 的值为 2 的时候才删除,删除成功返回 true,否则返回 false
        boolean code1 = jsonObject1.remove("code", "2");

Note: The element to be removed is not in the JSONObject and no exception will be thrown.


Delete the data in JSONArray: You can jsonArray.size()get the number of JSONObject in JSONArray through .

        // 移除索引为 0 的 JSONObject
        boolean remove1 = jsonArray.remove("0");
        // 移除指定的 JSONObject
        boolean remove = jsonArray.remove(jsonArray.getJSONObject(0));
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (Object obj : jsonArray) {
    
    
            jsonObjects.add((JSONObject) obj);
        }
        // 移除所有 JSONObject
        boolean b = jsonArray.removeAll(jsonObjects);

Note: The element to be removed is not in the JSONArray and no exception will be thrown.

Remove and replace all data in JSONArray:

		// detailArr 是 JSONArray
		Map<Integer, JSONObject> map = new HashMap<>();
        int size = detailArr.size();
        for (int i = 0; i < size; i++) {
    
    
            JSONObject item = detailArr.getJSONObject(0);
            map.put(i, item);
            detailArr.remove(0);
        }
        for (int i = 0; i < size; i++) {
    
    
            detailArr.add(map.get(i));
        }

new data

JSONObject new data:

        JSONObject jsonObject = new JSONObject();
        // 插入 key-value ,如果已存在,则覆盖原来的 key 的 value,返回 Object
        Object tip = jsonObject.put("tip", "脱下长衫,摆摊致富");
        Map<String, Object> map = new HashMap<>();
        map.put("name", "大学生");
        map.put("major","通信工程");
        map.put("age", 22);
        // 插入 map
        jsonObject.putAll(map);
        // 插入 key-value ,如果 key 已存在,则插入失败且返回已有的 key-value
        Object tip1 = jsonObject.putIfAbsent("tip", "摆摊摆摊,日赚九千");
        // 将 map 作为 JSONObject 插入
        jsonObject.put("map", map);

JSONArray new data: similar to JSONObject, but <index + Object>, and JSONObject is <key-value>.

Note: JSONArray inserts JSONObject twice for the same index, the effect is as follows:

change the data

        String str = "{\"code\":\"1\",\"status\":\"success\",\"target\":\"年入百万\",\"msg\":{\"seq\":\"20230424\",\"weather\":\"晴\",\"salary\":9000.00,\"job\":\"摆地摊\"},\"goods\":{\"sum\":2000.00,\"manufacturer\":{\"address\":\"青口\",\"boss\":\"张三\"},\"details\":[{\"name\":\"土豆\",\"weight\":\"500斤\"},{\"name\":\"豆腐\",\"weight\":\"250斤\"}]}}";
        JSONObject jsonObject = JSONObject.parseObject(str);
        // 替换对应 key 的 value
        jsonObject.replace("code", 1);
        JSONObject msg = jsonObject.getJSONObject("msg");
        msg.replace("salary", 10000.00);
        jsonObject.replace("msg", msg);

        // 替换对应 key 的 oldValue 为 newValue,如果 oldValue 不存在,则不替换
        jsonObject.replace("target", "年入十万", "年入千万");

Note: jsonObject put(String key, Object value)can also achieve the effect of replace.

Guess you like

Origin blog.csdn.net/m0_54355172/article/details/130336130