简体   繁体   中英

Dynamic object mapping using Jackson

I have a JSON request of the form:

{
  "type": "Car"
  "data": {
      "object": {
          "id": "1"
          "color": "Red"
          "plate": "J124D"
      },
      "owner": {
          "name": "John"
      }
  }
}

Now, the type field dictates the content of the object field. In the example above, the type = Car means the object container will have id, color and plate fields. But, if the type = Plane, the Object field will have id, wingspan, manufacturer etc. Basically, the type field will dictate dynamically what Java object corresponds to "object". I am fairly new to Jackson, so I was looking for some pointers on how to achieve this type of dynamic mapping in code. So far I have this,

public class Request {
    @JsonProperty
    String type;

    @JsonProperty
    Data data; // Probably need a custom deserializer here?
}

The other difficulty is the usage of Request. Data would probably have to be cast into something like CarData or PlaneData so that callers could easily do request.getType() and then extract data from the request casted to the appropriate type of data (Car or Plane).

A simple way to do it is using a Map<String, Object> to map the data property:

public class Request { 

    private String type;
    private Map<String, Object> data;

    // Getters and setters
}

You may find this answer useful.

Create a POJO for object tag. Using JSONObject class you can map the value to java POJO accordingly.

Ref: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

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