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

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

问题描述

我正在使用杰克逊将我的对象转换为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中显示为值, name在标签中显示为标签。杰克逊的文档尚不明确,我尝试了每个注释,即使它们看起来很像我需要的注释,但我无法获得 name 出现为 label id 在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天全站免登陆