Java实现JSON字符串与对象相互转换

Java实现JSON字符串与对象相互转换

观前提示:

本文所使用的IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141。

1. Jackon ObjectMapper

引用相关jar包

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

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

实体 Person.java

package testJsonToEntity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder(value = {"ID","name","age"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {

    @JsonProperty("ID")
    private String id;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String name;

    private int age;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

注意

  1. @JsonPropertyOrder此注解作用是把属性排序。

  2. @JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段。

  3. @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name。

  4. @JsonInclude(Include.NON_NULL)的作用:jackson 实体转json 为NULL的字段不参加序列化(即不显示)

测试类Test.java

package testJsonToEntity;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    private static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {

        Person p = new Person();
        p.setId("1111");
        p.setAge(18);
        String jsonStr = mapper.writeValueAsString(p);
        System.out.println(jsonStr);

        String json = "{\"Id\":\"1111\",\"age\":18,\"sex\":\"male\"}";
        Person p1 = mapper.readValue(json, Person.class);
        System.out.println(p1.toString());
    }
}

结果为

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值