简体   繁体   中英

How to create a POJO for the following json?

I want to map following json to a pojo using jackson.

{
  "colors": {
    "red": {
      "colorCode": "#FF0000"
    },
    "green": {
      "colorCode": "#00FF00"
    },
    "blue": {
      "colorCode": "#0000FF"
    }
  }
}

Is there any possible way to create a single POJO without having to create POJOs for each color because every color contains same parameter(colorCode)?

Note: I tried using @jsonAlias but it wont work because it overwrites that parameter.

The simplest solution would be to use a Map < String, Color > (or maybe Enum if you have a fixed list of colors)

public class Color{
  private String colorCode;

  //constructor, getter, setter
} 
public class Pojo{
   private Map<String,Color> colors;

  //constructor, getter, setter
}

The name of the color is just the name. Unless blue Behaves differently then Red, then they should not be separate classes.

Public class Color{
Private string colorCode;
Private string title

Color(string colorCode, string title){
This.colorCode =colorCode;
This.title = title;
}

Getter setters etc

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