Jackson 使用和注意项

依赖maven:

   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.5</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.5</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.5</version>
        </dependency>

code:

User:

import lombok.*;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
}

Birthday:

import lombok.*;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Birthday {
    private String birthday;
}

User2:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User2 {
    private int id;
    private String name;
    private String email;
//    private String address;
//    private Birthday birthday;
}

1.查看基础类型的序列化与反序列化:

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class test{

    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) {
        
        User user = new User();
        user.setAddress("asdf");
        user.setAddress("中国河南省");
        user.setEmail("xiaokui_wingfly@sina.com.cn");
        user.setId(1);
        user.setName("X-rapido");
        user.setBirthday(new Birthday("2015-08-06"));

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("a", "1");
        map.put("b", "2");
        map.put("c", "3");
        map.put("list", list);

        String []sz = {"a","b","c"};

        try {
            System.out.println(objectMapper.writeValueAsString(user));
            System.out.println(objectMapper.writeValueAsString(list));
            System.out.println(objectMapper.writeValueAsString(map));
            System.out.println(objectMapper.writeValueAsString(sz));

            String s = "{\"name\":\"X-rapido\"}";
            // Json转换JavaBean
            User a = objectMapper.readValue(s, User.class);
            System.out.println(a.getName());

            // JavaBean转换Json
            System.out.println(objectMapper.writeValueAsString(a));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
["a","b","c"]
{"a":"1","b":"2","c":"3","list":["a","b","c"]}
["a","b","c"]
X-rapido
{"id":0,"name":"X-rapido","email":null,"address":null,"birthday":null}

2.有这么种情况,就是字符串反序列化为对象,但是字符串中的很多字段我都不需要,只需要一部分,这个时候怎么反序列化:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;

import java.io.IOException;

public class test{

    private final static ObjectMapper objectMapper = new ObjectMapper();
    public static void main(String[] args) {

        //当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能,
        //因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略
        objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        User user = new User();
        user.setAddress("asdf");
        user.setAddress("中国河南省");
        user.setEmail("xiaokui_wingfly@sina.com.cn");
        user.setId(1);
        user.setName("X-rapido");
        user.setBirthday(new Birthday("2015-08-06"));

        try {
            System.out.println("========begin=======");
            val content=objectMapper.writeValueAsString(user);
            System.out.println(content);
            User2 u=objectMapper.readValue(content,User2.class);
            System.out.println(objectMapper.writeValueAsString(u));
            System.out.println("========end=======");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

========begin=======
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn"}
========end=======

注意:

        objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

如果不加这个会报错:

========begin=======
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "address" (class com.qhong.json.User2), not marked as ignorable (3 known properties: "id", "email", "name"])
 at [Source: {"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}; line: 1, column: 76] (through reference chain: com.qhong.json.User2["address"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
    at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:839)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1045)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1352)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1330)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:264)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)
    at com.qhong.json.test.main(test.java:29)

3.怎么反序列化对象数组:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class test{
    private final static ObjectMapper objectMapper = new ObjectMapper();
    public static void main(String[] args) {
        //当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能,
        //因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略
        objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        List<User> arr= Arrays.asList(
                    new User(1, "name1", "email1", "address1", new Birthday("2016-08-01")),
                    new User(2 ,"name2", "email2", "address2", new Birthday("2016-08-02")),
                    new User(3, "name3", "email3", "address3", new Birthday("2016-08-03"))
        );

        try {
            System.out.println("========begin=======");
            val content=objectMapper.writeValueAsString(arr);
            System.out.println(content);
            List<User> list=objectMapper.readValue(content,new com.fasterxml.jackson.core.type.TypeReference<List<User>>(){});
            System.out.println(objectMapper.writeValueAsString(list));
            System.out.println("另外的方式:");
           // List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
            List<User> list2=objectMapper.readValue(content,objectMapper.getTypeFactory().constructCollectionType(ArrayList.class,User.class));
            System.out.println(objectMapper.writeValueAsString(list2));
            System.out.println("========end=======");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

========begin=======
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
另外的方式:
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
========end=======

 还有一些其他的特殊情况,比如json对象key没有双引号等

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List;

public class test2{
    private final static  ObjectMapper mapper= new ObjectMapper();
        public static void main(String[] args) {
          try {
              mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
              // 如果为空则不输出
              mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
              // 对于空的对象转json的时候不抛出错误
              mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
              // 禁用序列化日期为timestamps
              mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
              // 禁用遇到未知属性抛出异常
              mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
              // 视空字符传为null
              mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

              // 低层级配置
              mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
              // 允许属性名称没有引号
              mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
              // 允许单引号
              mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
              // 取消对非ASCII字符的转码
              mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);

              //mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
              String str = " [\n" +
                      "    {\n" +
                      "        \"symbol\": \"sh603111\", \n" +
                      "        \"code\": \"603111\", \n" +
                      "        \"name\": \"康尼机电\", \n" +
                      "        \"trade\": \"14.530\", \n" +
                      "        \"pricechange\": \"0.770\", \n" +
                      "        \"changepercent\": \"5.596\", \n" +
                      "        \"buy\": \"14.530\", \n" +
                      "        \"sell\": \"14.540\", \n" +
                      "        \"settlement\": \"13.760\", \n" +
                      "        \"open\": \"13.820\", \n" +
                      "        \"high\": \"14.540\", \n" +
                      "        \"low\": \"13.820\", \n" +
                      "        \"volume\": 18591408, \n" +
                      "        \"amount\": 266138177, \n" +
                      "        \"ticktime\": \"15:00:00\", \n" +
                      "        \"per\": 44.339, \n" +
                      "        \"pb\": 7.731, \n" +
                      "        \"mktcap\": 1072870.86225, \n" +
                      "        \"nmc\": 697004.688465, \n" +
                      "        \"turnoverratio\": 3.87563\n" +
                      "    }, \n" +
                      "    {\n" +
                      "        \"symbol\": \"sz300355\", \n" +
                      "        \"code\": \"300355\", \n" +
                      "        \"name\": \"蒙草生态\", \n" +
                      "        \"trade\": \"12.330\", \n" +
                      "        \"pricechange\": \"0.620\", \n" +
                      "        \"changepercent\": \"5.295\", \n" +
                      "        \"buy\": \"12.330\", \n" +
                      "        \"sell\": \"12.340\", \n" +
                      "        \"settlement\": \"11.710\", \n" +
                      "        \"open\": \"11.640\", \n" +
                      "        \"high\": \"12.580\", \n" +
                      "        \"low\": \"11.640\", \n" +
                      "        \"volume\": 142839605, \n" +
                      "        \"amount\": 1741652819, \n" +
                      "        \"ticktime\": \"15:06:03\", \n" +
                      "        \"per\": 35.229, \n" +
                      "        \"pb\": 6.27, \n" +
                      "        \"mktcap\": 1978030.485873, \n" +
                      "        \"nmc\": 1428385.32288, \n" +
                      "        \"turnoverratio\": 12.33009\n" +
                      "    }\n" +
                      "]";
              System.out.println(str);
              List<riseInfo> list = mapper.readValue(str, new TypeReference<List<riseInfo>>() {
              });
              System.out.println(list.size());
          }catch (Exception ex){
              System.out.println(ex.getMessage());
              System.out.println(ex.getStackTrace());
          }
        }
}

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
class riseInfo {
    private String symbol;
    private String code;
    private String name;
}

Output:

 [
    {
        "symbol": "sh603111", 
        "code": "603111", 
        "name": "康尼机电", 
        "trade": "14.530", 
        "pricechange": "0.770", 
        "changepercent": "5.596", 
        "buy": "14.530", 
        "sell": "14.540", 
        "settlement": "13.760", 
        "open": "13.820", 
        "high": "14.540", 
        "low": "13.820", 
        "volume": 18591408, 
        "amount": 266138177, 
        "ticktime": "15:00:00", 
        "per": 44.339, 
        "pb": 7.731, 
        "mktcap": 1072870.86225, 
        "nmc": 697004.688465, 
        "turnoverratio": 3.87563
    }, 
    {
        "symbol": "sz300355", 
        "code": "300355", 
        "name": "蒙草生态", 
        "trade": "12.330", 
        "pricechange": "0.620", 
        "changepercent": "5.295", 
        "buy": "12.330", 
        "sell": "12.340", 
        "settlement": "11.710", 
        "open": "11.640", 
        "high": "12.580", 
        "low": "11.640", 
        "volume": 142839605, 
        "amount": 1741652819, 
        "ticktime": "15:06:03", 
        "per": 35.229, 
        "pb": 6.27, 
        "mktcap": 1978030.485873, 
        "nmc": 1428385.32288, 
        "turnoverratio": 12.33009
    }
]
2

 

添加配置即可!

http://blog.csdn.net/langzi7758521/article/details/52072457

http://www.cnblogs.com/kakag/p/5054772.html

http://www.cnblogs.com/dupang/p/5673097.html

https://codeday.me/bug/20170221/3548.html

posted @ 2017-09-17 21:29  hongdada  阅读(3323)  评论(0编辑  收藏  举报