简体   繁体   中英

Jackson annotations for easy JSON deserialization

I have a JSON file which looks like this:

{
    "root": [
              {
                "id": "abc1",
                "x": "x1",
                "y": "y1"
              },
              {
                "id": "abc2",
                "x": "x2",
                "y": "y2"
              },
       ...
            ]
}

I want to deserialize this with Jackson to an object from a class that looks like this:

Class A {
    Map<String, String> x;
    Map<String, String> y;
}

At the end I want the maps inside the A object to look like:

x = { (abc1, x1), (abc2, x2) }, y = { (abc1, y1), (abc2, y2) }

Is there a way to annotate this class with Jackson so that I can do this deserialization in one line? I couldn't find a way to do that without having to change the design of class A.

Ideally, X and Y would be separated into two objects with IDs. If it is at all possible to restructure your JSON or Java object to better fit your needs you would be following best practice and your code would be easier to follow--I understand that's not always an option.

One thing you can do is create a custom class that mimics the structure of the objects inside of your array. Then you can annotate a constructor and pass in a list of this custom object. Something like this:

public class A {
    private Map<String, String> x;
    private Map<String, String> y;

    @JsonCreator
    public A(@JsonProperty("root") List<Entity> entities) {
        for (Entity entity : entities) {
            x.put(entity.getId, entity.getX());
            y.put(entity.getId, entity.getY());
        }
    }

    public static class Entity {
        private String id;
        private String x;
        private String y;

        public String getId() {
            return id;
        }

        public String setId(String id) {
            this.id = id;
        }

        public String getX() {
            return x;
        }

        public String setX(String x) {
            this.x = x;
        }

        public String getY() {
            return y;
        }

        public String setY(String y) {
            this.y = y;
        }
    }
}

I'm not sure what you mean by "deserialize in one line". If your looking for an easier alternative, the only other thing that could satisfy your requirements is a custom deserializer, which is more complicated.

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