com.fasterxml.jackson.databind.ObjectMapper操作对象和集合的一些相互转换用法

  • 概述
  • JacksonTest
  • AccountBean
  • Birthday

概述

原文链接:http://blog.csdn.net/u011506468/article/details/47342667

最近用到了ObjectMapper,做了些实验。主要有以下一些转换方式:

  • JavaBean(Entity/Model)转换成JSON
  • 将Map集合转换成Json字符串
  • 将List集合转换成json
  • 将json字符串转换成JavaBean对象
  • 将json字符串转换成List集合
  • 将json字符串转换成List集合
  • Json字符串转换成Array数组
  • Json字符串转换成Map集合

代码如下,全部copy过去即可

JacksonTest

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTest {
    private JsonGenerator jsonGenerator = null;
    private ObjectMapper objectMapper = null;
    private AccountBean bean = null;

    public static void main (String[] args) {
        JacksonTest test = new JacksonTest();
        test.init();
        /* JavaBean(Entity/Model)转换成JSON */
        //test.writeEntityJSON();
        /* 将Map集合转换成Json字符串 */
        //test.writeMapJSON();
        /* 将List集合转换成json */
        //test.writeListJSON();
        /* 将json字符串转换成JavaBean对象 */
        //test.readJson2Entity();
        /* 将json字符串转换成List<Map>集合 */
        //test.readJson2List();
        /*将json字符串转换成List<T>集合*/
        //test.readJson2ListT();
        /*  Json字符串转换成Array数组 */
        //test.readJson2Array();
        /* Json字符串转换成Map集合 */
        test.readJson2Map();

        test.destory();
    }
    /* Json字符串转换成Map集合 */
    public void readJson2Map() {
        String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                    "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
        try {
            Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
            System.out.println(maps.size());
            Set<String> key = maps.keySet();
            Iterator<String> iter = key.iterator();
            while (iter.hasNext()) {
                String field = iter.next();
                System.out.println(field + ":" + maps.get(field));
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*  Json字符串转换成Array数组 */
    public void readJson2Array() {
        String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
        try {
            AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
            System.out.println(arr.length);
            for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*将json字符串转换成List<T>集合*/
    public void readJson2ListT() {
        String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                    "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
        try {
            List<AccountBean> list = objectMapper.readValue(json, new TypeReference<List<AccountBean>>(){} );
            System.out.println(list.size());
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /* 将json字符串转换成List<Map>集合 */
    public void readJson2List() {
        String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                    "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
        try {
            List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
            System.out.println(list.size());
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                Set<String> set = map.keySet();
                for (Iterator<String> it = set.iterator();it.hasNext();) {
                    String key = it.next();
                    System.out.println(key + ":" + map.get(key));
                }
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /* 将json字符串转换成JavaBean对象 */
    public void readJson2Entity() {
        String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
        try {
            AccountBean acc = objectMapper.readValue(json, AccountBean.class);
            System.out.println(acc.getName());
            System.out.println(acc);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /* 将List集合转换成json */
    public void writeListJSON() {
        try {
            List<AccountBean> list = new ArrayList<AccountBean>();
            list.add(bean);

            bean = new AccountBean();
            bean.setId(2);
            bean.setAddress("address2");
            bean.setEmail("email2");
            bean.setName("haha2");
            list.add(bean);

            System.out.println("jsonGenerator");
            //list转换成JSON字符串
            jsonGenerator.writeObject(list);
            System.out.println();
            System.out.println("ObjectMapper");
            //用objectMapper直接返回list转换成的JSON字符串
            System.out.println("1###" + objectMapper.writeValueAsString(list));
            System.out.print("2###");
            //objectMapper list转换成JSON字符串
            objectMapper.writeValue(System.out, list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /* 将Map集合转换成Json字符串 */
    public void writeMapJSON() {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", bean.getName());
            map.put("account", bean);
            bean = new AccountBean();
            bean.setAddress("china-Beijin");
            bean.setEmail("[email protected]");
            map.put("account2", bean);

            System.out.println("jsonGenerator");
            jsonGenerator.writeObject(map);
            System.out.println("");

            System.out.println("objectMapper");
            objectMapper.writeValue(System.out, map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /* JavaBean(Entity/Model)转换成JSON */
    public void writeEntityJSON() {

        try {
            System.out.println("jsonGenerator");
            //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
            jsonGenerator.writeObject(bean);
            System.out.println();

            System.out.println("ObjectMapper");
            //writeValue具有和writeObject相同的功能
            objectMapper.writeValue(System.out, bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* 初始化 */
    public void init() {
        bean = new AccountBean();
        bean.setAddress("china-Guangzhou");
        bean.setEmail("ho[email protected]");
        bean.setId(1);
        bean.setName("hoojo");
        objectMapper = new ObjectMapper();
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* 释放资源 */
    public void destory() {
        try {
            if (jsonGenerator != null) {
                jsonGenerator.flush();
            }
            if (!jsonGenerator.isClosed()) {
                jsonGenerator.close();
            }
            jsonGenerator = null;
            objectMapper = null;
            bean = null;
            System.gc();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AccountBean

public class AccountBean {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;

    //getter、setter

    @Override
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Birthday getBirthday() {
        return birthday;
    }

    public void setBirthday(Birthday birthday) {
        this.birthday = birthday;
    }

}

Birthday


public class Birthday {
    private String birthday;

    public Birthday(String birthday) {
        super();
        this.birthday = birthday;
    }

    //getter、setter

    public Birthday() {}

    @Override
    public String toString() {
        return this.birthday;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-12-08 00:12:41

com.fasterxml.jackson.databind.ObjectMapper操作对象和集合的一些相互转换用法的相关文章

com.fasterxml.jackson.databind.ObjectMapper. .readValue .convertValue

String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}"; Student stu = null; List<Student> list = null; try { ObjectMapper objec

SpringBoot JPA懒加载异常 - com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy

问题与分析 某日忽然发现在用postman测试数据时报错如下: com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.cbxsoftware.cbx.attachment.entity.RefAttachment#c109ec36e60c4a89a10eabc72416d984] - no Session (through reference chain: com.cbxsoftw

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field &quot;FileSize&quot;

请求阿里云的OSS接口图片信息,返回json格式的数据,通过ObjectMapper将json转为Image对象时候报错转换失败 将json转对象的代码: String jsonStr = "{\n" + " \"FileSize\": {\"value\": \"25929\"},\n" + " \"Format\": {\"value\": \"

【jackson 异常】com.fasterxml.jackson.databind.JsonMappingException异常处理

项目中,父层是Gene.java[基因实体]  子层是Corlib.java[文集库实体],一种基因对用多个文集库文章 但是在查询文集库这个实体的时候报错:[com.fasterxml.jackson.databind.JsonMappingException] 1 com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassis

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field &quot;ExceptionId&quot;

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ExceptionId" (class com.tongyan.ems.model.request.SynchronizedBean), not marked as ignorable (2 known properties: "cityIds", "exceptionId"]

com.fasterxml.jackson.databind.JsonMappingException

问题描述:在对订单进行上传的时候,其实就是一个excel文件,发现controller对业务层代码调用老是出问题,排查原因时发现原来时被同事的AOP给拦截了,用JackSon对流进行打印导致的异常. Caused by: com.fasterxml.jackson.databind.JsonMappingException: Failed to load class 'sun.nio.ch.FileChannelImpl$Access4JacksonSerializer0370ba83': co

meta对象写入json错误:com.cutt.zhiyue.android.api.io.exception.JsonFormaterException: com.fasterxml.jackson.databind.JsonMappingException

首先说明出现的原因:json这个东西不够智能,在解析javabean对象中的getter和setter方法时,会把两个方法命名十分相近的方法当成一个.从而形成异常. 解决办法:重新命名方法名. 同时需要注意:json在写入某一个meta对象时,会将其所关联的meta对象统统捋一遍(不一定是重置,可能仅仅是遍历一下). 这是我们的json写入异常: com.cutt.zhiyue.android.api.io.exception.JsonFormaterException: com.fasterx

at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields异常

at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:666) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) at com.fasterxml.jackson.databind.ser.impl.IndexedListSe

JSON parse error: Cannot deserialize instance of `int` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc

代码程序: @PostMapping("selectById") @ResponseBody public Result selectById(@RequestBody int id) { Result result =new Result(); List<User> list = userService.selectById(id); if(list.size()==1){ result.setCode("000"); result.setMsg(&q