如何将对象的嵌套JSON输入解析为泽西?

时间:2016-03-12 18:25:10

标签: java json api jersey

我正在将输入传递给我的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方法中自动实例化过滤器对象?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您可以使用jackson mapper

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

或者如果您使用泽西岛

<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;
}