简体   繁体   中英

Map JSON Response to POJO (with different names)

I know there are numerous posts out there for a similar problem, but mine seems to be a bit different. I am reading in a bunch of JSON and would like to build POJO from it, but I don't want to use the names of the JSON result. Is there a way to "map" the element names in JSON to the attributes in my POJOs (using gson or Jackson maybe)?

It's worth mentioning this application is being built for Android.

Thanks in advance!

If you're using Gson , you can append an attribute to your objects, like so:

@SerializedName("ServicesResult")
public String services;

Where "ServicesResult" is the actual name of the element in the JSON.

With Jackson, you have multiple options:

  • Use @JsonProperty("name") annotation to indicate name to use in JSON, add directly or use mix-in annotations (external)
  • Specify PropertyNamingStrategy to convert from "Java name" to "JSON name" (there is default java<->c-style converter bundled with 1.9)
  • Modify AnnotationIntrospector to change the name using some other mechanism than annotations

Jackson will also interpret the Basic package javax.xml.bind.annotation

If you use those annotations you can readily move between Json/XML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM