Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping JSON names to Java class fields/methods (Jackson Parser)

Summary

How can I map a JSON name to a Java class' field name that might be (slightly) different when using the Jackson parser?

Details

I have incoming JSON documents I would like to convert to a Java object using the Jackson parser. This works well for where the JSON names match the eventual Java object field names (I am doing this within the Play Framework).

However some JSON names in the incoming JSON document do not lend themselves to nice Java field names. Changing all the existing JSON documents to use proper Java naming conventions is currently not feasible.

For example

{
  "goodName": "value",
  "not-so-handy": "value"
}

I can't create a Java class with a field name of "not-so-handy" since that is not a legal name in Java.

How can I translate an incoming JSON name to a designated Java class' field name using the Jackson parser?

like image 606
Friedrich 'Fred' Clausen Avatar asked Jul 23 '14 03:07

Friedrich 'Fred' Clausen


1 Answers

Use @JsonProperty :

@JsonProperty("goodName")
public String goodName;

@JsonProperty("not-so-handy")
public String notSoHandy;

This will solve the issue.

like image 131
Literally Illiterate Avatar answered Oct 26 '22 08:10

Literally Illiterate