java json 修改字段_我们如何使用Java中的Jackson来更改JSON中的字段名称?

杰克逊注释@JsonProperty上使用期间的属性或方法的序列或反串行化的JSON。它带有一个可选的' name '参数,当属性名称与JSON中的' key '名称不同时,该参数很有用。默认情况下,如果键名称与属性名称匹配,则将值映射到属性值。

在下面的示例中,我们可以使用@JsonProperty注解更改JSON中的字段名称。

示例import java.io.IOException;

import com.fasterxml.jackson.databind.*;

import com.fasterxml.jackson.annotation.JsonProperty;

public class JsonPropertyAnnotationTest {

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

ObjectMapper mapper = new ObjectMapper();

mapper.enable(SerializationFeature.INDENT_OUTPUT);

User user = new User("Sai", "Adithya", "9959984000", "0402358700");

String data = mapper.writeValueAsString(user);

System.out.println(data);

}

}

//用户类别

class User {

@JsonProperty("first-name")

public String firstName;

@JsonProperty("last-name")

public String lastName;

@JsonProperty("mobile-phone")

public String mobilePhone;

@JsonProperty("home_phone")   public String workPhone;

public User(String firstName, String lastName, String mobilePhone, String workPhone) {

super();

this.firstName = firstName;

this.lastName = lastName;

this.mobilePhone = mobilePhone;

this.workPhone = workPhone;

}

}

输出结果{

"first-name" : "Sai",

"last-name" : "Adithya",

"mobile-phone" : "9959984000",

"home_phone" : "0402358700"

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值