Java对象与Map的互转
1.引入fastjson
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<!--fastjson结束-->
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<String, Object> 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<String,Object> 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"}
3.扩展
从字符串转对象,待转换的对象为泛型时,使用:
UserDTO<T> obj = JSON.parseObject("jsonStr", new TypeReference<UserDTO<T>>(){});