如何使用 Jackson 更改 JSON 中的字段名称 [英] How to change a field name in JSON using Jackson

查看:87
本文介绍了如何使用 Jackson 更改 JSON 中的字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jackson 将我的对象转换为 json.该对象有 2 个字段:

I'm using jackson to convert an object of mine to json. The object has 2 fields:

@Entity
public class City {
   @id
   Long id;
   String name;
   public String getName() { return name; }
   public void setName(String name){ this.name = name; }
   public Long getId() { return id; }
   public void setName(Long id){ this.id = id; }
}

因为我想将它与 jQuery 自动完成功能一起使用,所以我希望id"在 json 中显示为值",而名称"显示为标签".jackson 的文档对此并不清楚,我已经尝试了所有注释,即使远程看起来它也能满足我的需要,但我无法让 name 显示为 labelid 在 json 中显示为 value.

Since I want to use this with the jQuery auto complete feature I want 'id' to appear as 'value' in the json and 'name' to appear as 'label'. The documentation of jackson is not clear on this and I've tried every annotation that even remotely seems like it does what I need but I can't get name to appear as label and id to appear as value in the json.

有谁知道如何做到这一点,或者这是否可能?

Does anyone know how to do this or if this is possible?

推荐答案

您是否尝试过使用 @JsonProperty?

Have you tried using @JsonProperty?

@Entity
public class City {
   @id
   Long id;
   String name;

   @JsonProperty("label")
   public String getName() { return name; }

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

   @JsonProperty("value")
   public Long getId() { return id; }

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

这篇关于如何使用 Jackson 更改 JSON 中的字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆