Jackson使用:String 与对象互转、Jackson 从 json 字符串转换出对象

一、从json字符串转换出对象

Pager类:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class Pager {
    private int nowPage;
    private int pageSize;


    public int getNowPage() {
        return nowPage;
    }
    public void setNowPage(int nowPage) {
        this.nowPage = nowPage;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

}

使用@JsonIgnoreProperties(ignoreUnknown=true) 忽略没有传入的属性,否则每一个set方法都必须在字符串中找到对照,找不到就会报错。

转换

ObjectMapper objectMapper = new ObjectMapper();
Pager pager = objectMapper.readValue(jsonString, Pager.class);

其中 jsonString 为 json 字符串,转换得到一个 Pager 类对象。

转自:https://blog.csdn.net/chemmuxin1993/article/details/52839463 

二、String与对象互转

 jackson转换工具
   

 private static final ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

使用 对象转 json

String str = objectMapper.writeValueAsString(new MessageEntity());

json 转对象

List<String> tidList = objectMapper.readValue(tidListSrt,
 new TypeReference<List<String>>() {});


转自:https://blog.csdn.net/csdn2193714269/article/details/78844753 
 

猜你喜欢

转载自blog.csdn.net/u011314442/article/details/83895121