您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何使用Jackson在Java中为字段定义替代名称?

2024/6/22 8:14:56发布21次查看
the @jsonalias annotation can define one or more alternate names for the attributes accepted during the deserialization, setting the json data to a java object. but when serializing, i.e. getting json from a java object, only the actual logical property name is used instead of the alias.
syntax@target(value={annotation_type,field,method,parameter})@retention(value=runtime)public @interface jsonalias
example的中文翻译为:示例import com.fasterxml.jackson.annotation.*;import com.fasterxml.jackson.core.*;import com.fasterxml.jackson.databind.*;import java.io.*;public class objecttojsontest { public static void main(string[] args) throws jsonprocessingexception { objectmapper mapper = new objectmapper(); technology tech = new technology("java", "oracle"); employee emp = new employee(110, "raja", tech); string jsonwriter = mapper.writerwithdefaultprettyprinter().writevalueasstring(emp); system.out.println(jsonwriter); }}// technology classclass technology { @jsonproperty("skill") private string skill; @jsonproperty("subskill") @jsonalias({"sskill", "mysubskill"}) private string subskill; public technology(){} public technology(string skill, string subskill) { this.skill = skill; this.subskill = subskill; } public string getskill() { return skill; } public void setskill(string skill) { this.skill = skill; } public string getsubskill() { return subskill; } public void setsubskill(string subskill) { this.subskill = subskill; }}// employee classclass employee { @jsonproperty("empid") private integer id; @jsonproperty("empname") @jsonalias({"ename", "myename"}) private string name; @jsonproperty("emptechnology") private technology tech; public employee(){} public employee(integer id, string name, technology tech){ this.id = id; this.name = name; this.tech = tech; } public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public technology gettechnology() { return tech; } public void settechnology(technology tech) { this.tech = tech; }}
输出{ "technology" : { "skill" : "java", "subskill" : "oracle" }, "empid" : 110, "empname" : "raja", "emptechnology" : { "skill" : "java", "subskill" : "oracle" }}
以上就是如何使用jackson在java中为字段定义替代名称?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product