ObjectMapper java对象和json字符串 互相转换

时间:2020-05-29 23:35:08   收藏:0   阅读:85
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

public class ObjectMapperTest {
    @Test
    public void test() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        Box box = new Box();
        box.setId(1);
        box.setHeight(100);
        box.setWidth(200);
        box.setMessage("Hello,World!");

        /**
         * Java对象 -> JSON字符串
         *
         * 对象必须要有 getter/setter 否则会报错
         */
        String json = objectMapper.writeValueAsString(box);

        /**
         * JSON字符串 -> Java对象
         *
         * 对象除了 getter/setter 必须要有空构造函数 否则会报错 Cannot construct instance of <xxx类>
         */
        Box theBox = objectMapper.readValue(json, Box.class);
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!