我将输入传递给我的API,如下所示:

{
  "param1": "value1",
  "param2":"value2",
  "param3": {
               "min": "xyz",
               "max": "abc"
            }
}


我想将此JSON请求解析为类似的对象:

class Filter {
       String param1;
       String param2;
       //frequency object will consist of maximum and minimum attributes
       Frequency frequency

}


如何在我的API方法中自动实例化过滤器对象?

提前致谢。

最佳答案

您可以使用杰克逊映射器

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.2</version>
</dependency>


或者如果您改用Jersey

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.22.2</version>
</dependency>




ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"param1\":\"Bar\",\"param2\":\"Foo\",\"frequency\":{\"min\":0,\"max\":10}}";
Filter filter = mapper.readValue(jsonString, Filter.class);
System.out.println(mapper.writeValueAsString(filter));




public class Filter {
    public String param1;
    public String param2;
    public Frequency frequency;
}




public class Frequency {
    public int min;
    public int max;
}

09-10 06:39
查看更多