Interchange between Java Map, JSONObject, and entity classes


foreword

Using the library com.alibaba.fastjson2, most JSON conversion operations can be done.

For details, refer to the article: Java FASTJSON2, an extremely powerful and easy-to-use JSON library


Map, JSONObject, entity class conversion

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // map集合转Java实体类
        Map<String, Object> map = new HashMap<>();
        map.put("id", 123456);
        map.put("name", "张三");
        User user = JSON.parseObject(JSON.toJSONString(map), User.class);
        System.out.println(user); // User(id=123456, name=张三)

        // Java实体类转为Map集合
        Map map1 = JSON.parseObject(JSON.toJSONString(user), Map.class);
        System.out.println(map1); // {name=张三, id=123456}

        // Java实体类转JSONObject
        JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
        System.out.println(jsonObject); // {"name":"张三","id":123456}

        // JSONObject转Java实体类
        User user1 = jsonObject.toJavaObject(User.class);
        System.out.println(user1); // User(id=123456, name=张三)

        // String转JSONObject
        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.toString());
        System.out.println(jsonObject1); // {"id":123456,"name":"张三"}

        // JSONObject转String
        String string = JSON.toJSONString(jsonObject);
        System.out.println(string); // {"id":123456,"name":"张三"}

        // String转JSONObject
        JSONObject jsonObject2 = JSON.parseObject(string);
        System.out.println(jsonObject2); // {"id":123456,"name":"张三"}

        // map集合转JSONObject
        JSONObject jsonObject3 = JSON.parseObject(JSON.toJSONString(map), JSONObject.class);
        System.out.println(jsonObject3); // {"name":"张三","id":123456}

        // JSONObject转为Map集合
        Map map2 = JSON.parseObject(jsonObject.toString(), Map.class);
        System.out.println(map2); // {name=张三, id=123456}
    }
}

@Data
class User {
    
    
    private Integer id;
    private String name;
}

Guess you like

Origin blog.csdn.net/xiaohuihui1400/article/details/132360258