Jackson使用配置

Jackson可以实现Java对象与JSON字符串的转换

首先引入maven依赖


    com.fasterxml.jackson.core
    jackson-databind
    2.7.1


    com.fasterxml.jackson.dataformat
    jackson-dataformat-xml
    2.7.1

然后编写springmvc.xml配置文件


    
        
            
            
        
    

未使用配置文件测试

public class JackSon {
    public static void main(String[] args) throws JsonProcessingException {
        //1.创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper ();
        //2.将对象转为json
        TbBrand brand = new TbBrand (2L, "奥利奥小兵", "A");
        String jsonstr = mapper.writeValueAsString (brand);
        System.out.println ("将对象转为json:"+jsonstr);
        System.out.println ("数组转list:"+Arrays.asList (jsonstr));

        //设置序列化后的格式,INDENT_OUTPUT表示缩进输出,true表示试该配置生效
        mapper.configure(SerializationFeature.INDENT_OUTPUT,true);

        //3.将list集合转为json
        List brands = (List) Arrays.asList (jsonstr,new TbBrand (3L, "奥利奥赫本", "A"),new TbBrand (4L, "奥利奥赫本", "A"));
        String jsonlist = mapper.writeValueAsString (brands);
        System.out.println ("将list集合转为json:"+jsonlist);
    }
}

输出结果:

将对象转为json:{"id":2,"name":"奥利奥小兵","firstChar":"A"}
数组转list:[{"id":2,"name":"奥利奥小兵","firstChar":"A"}]
将list集合转为json:[ "{\"id\":2,\"name\":\"奥利奥小兵\",\"firstChar\":\"A\"}", {
  "id" : 3,
  "name" : "奥利奥赫本",
  "firstChar" : "A"
}, {
  "id" : 4,
  "name" : "奥利奥赫本",
  "firstChar" : "A"
} ]

常用注解介绍:


@JsonIgnore

使用放在实体类的getter方法上面,可以忽略此属性转换为json

@JsonInclude(Include.NON_EMPTY)

仅在属性不为空时序列化此字

@JsonProperty(value = “xxx”)

指定实体类序列化时的字段名,默认使用属性名

 

你可能感兴趣的:(Java)