欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

解决ObjectMapper.convertValue() 遇到的一些问题

程序员文章站 2022-07-09 13:23:32
源代码:public t convertvalue(object fromvalue, typereference tovaluetyperef) thr...

源代码:

public <t> t convertvalue(object fromvalue, typereference<?> tovaluetyperef) throws illegalargumentexception { return (t) _convert(fromvalue, _typefactory.constructtype(tovaluetyperef)); }

该方法用于用jackson将bean转换为map

例子:

list<sobject> sobjects = new objectmapper().convertvalue(map.get("list"), new typereference<list<sobject>>() { });

微服务中从其他服务获取过来的对象,如果从object强转为自定义的类型会报错,利用objectmapper转换。

objectmapper mapper = new objectmapper();
defaultresponse defaultresponse = proxy.getdata();
list<resource> resources = (<resource>) defaultresponse.getdata();  //这里的场景是:data是一个object类型的,但是它其实是一个list<resouce>,想把list中的每个对象分别转成可用的对象
for (int i = 0; i < servicedateresources.size(); i++) {
    resource resource = mapper.convertvalue(resources.get(i), resource.class);   //经过这步处理,resource就是可用的类型了,如果不转化会报错
}

在转换过程中有些属性被设置为空,这样就不需要转化

处理方法:

在需要转化的实体类商添加如下注解

@jsoninclude(include.non_null) 
@jsoninclude(include.include.always) 默认 
@jsoninclude(include.non_default) 属性为默认值不序列化 
@jsoninclude(include.non_empty) 属性为 空(“”) 或者为 null 都不序列化 
@jsoninclude(include.non_null) 属性为null 不序列化 

jackson objectmapper json字符串、对象bean、map、数组list互相转换常用的方法列举:

objectmapper mapper = new objectmapper();

1.对象转json字符串

user user=new user();
string userjson=mapper.writevalueasstring(user);

2.map转json字符串

map map=new hashmap();  
string json=mapper.writevalueasstring(map);

3.数组list转json字符串

student[] stuarr = {student1, student3};  
string jsonfromarr =  mapper.writevalueasstring(stuarr);

4.json字符串转对象

string expected = "{\"name\":\"test\"}";
user user = mapper.readvalue(expected, user.class);

5.json字符串转map

string expected = "{\"name\":\"test\"}";
map usermap = mapper.readvalue(expected, map.class);

6.json字符串转对象数组list

string expected="[{\"a\":12},{\"b\":23},{\"name\":\"ryan\"}]";
collectiontype listtype = mapper.gettypefactory().constructcollectiontype(arraylist.class, user.class);
list<user> userlist = mapper.readvalue(expected, listtype);

7.json字符串转map数组list<map<string,object>>

string expected="[{\"a\":12},{\"b\":23},{\"name\":\"ryan\"}]";
collectiontype listtype = mapper.gettypefactory().constructcollectiontype(arraylist.class, map.class);
list<map<string,object>> usermaplist = mapper.readvalue(expected, listtype);

8.jackson默认将对象转换为linkedhashmap:

string expected = "[{\"name\":\"ryan\"},{\"name\":\"test\"},{\"name\":\"leslie\"}]";
arraylist arraylist = mapper.readvalue(expected, arraylist.class);

9.json字符串与list或map互转的方法

objectmapper objectmapper = new objectmapper();
 //遇到date按照这种格式转换
 simpledateformat fmt = new simpledateformat("yyyy-mm-dd hh:mm:ss");
 objectmapper.setdateformat(fmt);
 
  string preference = "{name:'侯勇'}";
        //json字符串转map
  map<string, string> preferencemap = new hashmap<string, string>();
  preferencemap = objectmapper.readvalue(preference, preferencemap.getclass());
  
  //map转json字符串
  string result=objectmapper.writevalueasstring(preferencemap);

10.bean转换为map

list<map<string,string>> returnlist=new arraylist<map<string,string>>();
list<menu> menulist=menudaoimpl.findbyparentid(parentid);
objectmapper mapper = new objectmapper();
//用jackson将bean转换为map
returnlist=mapper.convertvalue(menulist,new typereference<list<map<string, string>>>(){});

objectmapper.convertvalue() 报错

报错信息如下:

com.fasterxml.jackson.databind.exc.invaliddefinitionexception: cannot construct instance of java.time.localdatetime (no creators, like default constructor, exist): cannot deserialize from object value (no delegate- or property-based creator) at [source: unknown; line: -1, column: -1] (through reference chain: net.too1.tplus.user.user.entity.user[“createtime”])

根据以上报错得知, 是java.time.localdatetime类型的原因. objectmapper 不能对localdatetime 序列化. 加上以下注解即可解决

@jsondeserialize(using = localdatetimedeserializer.class)
@jsonserialize(using = localdatetimeserializer.class)
@apimodelproperty(value = "创建时间")
@jsondeserialize(using = localdatetimedeserializer.class)
@jsonserialize(using = localdatetimeserializer.class)
private localdatetime createtime;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。