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.JSONString(inMap), UserDTO.class);
UserDTO userDTO2 = JavaObject((JSON) JSON(inMap), UserDTO.class);
//对象 -> Map
Map map = JSONObject.JSONString(userDTO), Map.class);
Map<String,Object> map2 = JSONObject.JSONString(userDTO));
System.out.String());
System.out.String());
System.out.println("----------------------");
System.out.String());
System.out.String());
}
}
2.3 结果
UserDTO(id=123, name=yang, age=22)
object toUserDTO(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>>(){});
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论