Spring REST Controller映射JSON

时间:2018-07-18 10:01:24

标签: java json spring rest

想知道是否有人可以帮助我。我有一个JSON请求

{
    "blue": "blue",
    "red": "red",
    "greens" : {
        "lightGreen": "lightGreen",
        "darkGreen": "darkGreen"
    }
}

我想使用pojo映射到@RequestBody

这样做:

@PostMapping(path = "/colors", headers = "Accept=application/json")
public void generateClaimDocument(@Valid @RequestBody Colors colors) {
        if (colors != null) {
            service.doSomethingWithColors(colors);
        }
    }

蓝色和红色都可以正常工作,但是根本不映射JSON绿色对象。从来没有做过此事,所以有人可以阐明我该怎么做吗?

PoJo的:

public class Colors {

    private String blue;
    private String red;
    private Greens greens;
    //getters and setters
}

public class Greens {

    private String lightGreen;
    private String darkGreen;
    //getters and setters
}

1 个答案:

答案 0 :(得分:3)

使用您的代码找不到任何问题。尝试了以下示例:

    @RestController
    public static class ColorsService {

        @PostMapping(path = "/colors", headers = "Accept=application/json")
        public void generateClaimDocument(@Valid @RequestBody Colors colors) {
            if (colors != null) {
                System.out.println(colors);
            }
        }
    }

    public static class Colors {

        private String blue;
        private String red;
        private Greens greens;
        //getters and setters

        public String getBlue() {
            return blue;
        }

        public void setBlue(String blue) {
            this.blue = blue;
        }

        public String getRed() {
            return red;
        }

        public void setRed(String red) {
            this.red = red;
        }

        public Greens getGreens() {
            return greens;
        }

        public void setGreens(Greens greens) {
            this.greens = greens;
        }

        @Override
        public String toString() {
            return "Colors{" + "blue=" + blue + ", red=" + red + ", greens=" + greens + '}';
        }
    }

    public static class Greens {

        private String lightGreen;
        private String darkGreen;
        //getters and setters

        public String getLightGreen() {
            return lightGreen;
        }

        public void setLightGreen(String lightGreen) {
            this.lightGreen = lightGreen;
        }

        public String getDarkGreen() {
            return darkGreen;
        }

        public void setDarkGreen(String darkGreen) {
            this.darkGreen = darkGreen;
        }

        @Override
        public String toString() {
            return "Greens{" + "lightGreen=" + lightGreen + ", darkGreen=" + darkGreen + '}';
        }
    }

可准确显示您发布的内容:

Colors{blue=blue, red=red, greens=Greens{lightGreen=lightGreen, darkGreen=darkGreen}}