Java对象与Map的互转

2021-06-08 03:05

阅读:327

标签:json   data   str   print   对象   system   ast   group   package   

1.引入fastjson

        
        com.alibaba
            fastjson
            1.2.74

2.参考代码

2.1 Java对象UserDTO

package cn.yang37.demo.dto;

import lombok.Data;

@Data
public class UserDTO {
    private String id;
    private String name;
    private String age;
}

2.2 转换

package cn.yang37.demo.util;

import cn.yang37.demo.dto.UserDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

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

public class ParamUtils {

    public static void main(String[] args) {
        Map inMap = new HashMap();
        inMap.put("id","123");
        inMap.put("name","yang");
        inMap.put("age", "22");

        //Map -> 对象
        UserDTO userDTO = JSON.parseObject(JSON.toJSONString(inMap), UserDTO.class);
        UserDTO userDTO2 = JSONObject.toJavaObject((JSON) JSON.toJSON(inMap), UserDTO.class);

        //对象 -> Map
        Map map = JSONObject.parseObject(JSONObject.toJSONString(userDTO), Map.class);
        Map map2 = JSONObject.parseObject(JSON.toJSONString(userDTO));

        System.out.println(userDTO.toString());
        System.out.println(userDTO2.toString());
        System.out.println("----------------------");
        System.out.println(map.toString());
        System.out.println(map2.toString());
    }
}

2.3 结果

UserDTO(id=123, name=yang, age=22)
UserDTO(id=123, name=yang, age=22)
----------------------
{name=yang, id=123, age=22}
{"name":"yang","id":"123","age":"22"}

Java对象与Map的互转

标签:json   data   str   print   对象   system   ast   group   package   

原文地址:https://www.cnblogs.com/yang37/p/14537648.html


评论


亲,登录后才可以留言!