Jackson使用配置

博客介绍了Jackson可实现Java对象与JSON字符串的转换。先说明了引入maven依赖、编写springmvc.xml配置文件,还进行了未使用配置文件的测试。此外,介绍了常用注解,如@JsonIgnore、@JsonInclude、@JsonProperty等的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

首先引入maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.7.1</version>
</dependency>

然后编写springmvc.xml配置文件

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <!-- 使用构造器赋值 -->
            <constructor-arg value="UTF-8"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

未使用配置文件测试

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<TbBrand> 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”)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值