13

我正在尝试将 Java 对象转换为 Tomcat 中的 JSON(当前使用 Jackson)。基于 RESTful 请求中的字段,我只想序列化这些字段。我想支持对任何字段子集的请求,所以我想在运行时(动态地)这样做。

例如,假设我想支持 User 对象的部分序列化:

class User {
    private final String id;
    private final String firstName;
    private final String lastName;

    public User(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getId() { return id; }
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
}

如果我提出以下要求:

GET /users/{id}/?fields=firstName,lastName

我想得到类似的东西{"firstName":"Jack","lastName":"Johnson"}

如果我提出以下要求:

GET /users/{id}/?fields=firstName

我想得到类似的东西{"firstName":"Jack"}

Jackson 的JSON 视图能够定义要序列化的逻辑属性子集(通过 getter 或字段访问的事物)。但是,它们是静态定义的(使用注释)并且只能动态选择(每个序列化)。在实践中,我希望支持请求对象字段的任何子集,因此我可能拥有数千个 JSON 视图(10 个字段意味着 1,023 个子集!)。

什么 JSON 库在运行时支持部分序列化?

4

3 回答 3

1

We use Google GSON to convert back and forth between Java object and JSON. I am not sure if it has the functionality you are looking for but it is very easy to use and the docs are good too.

If you can't find a library that does what you need, I second the suggestion of using looser structured classes (like HashMap) or custom representation classes for being the link between your code and the JSON. This would add another layer or two but keep the complexity down. Good luck.

于 2010-09-20T18:46:16.730 回答
0

我认为 json-lib 和 flex-json 支持更动态/灵活的过滤。

对于 Jackson,一些用户所做的是使用 HashMaps 或 JsonNodes 作为更松散的结构并从那里进行过滤。

此外,虽然这在短期内对您没有帮助,但 Jackson 1.6 对 JsonNode(retainAll(String...names)、remove(String...names) 和可能的 ObjectMapper 都有改进,因为这是一个已知的改进领域.

于 2010-08-24T17:31:10.917 回答
0

Since Spring 4.2.0.Release, you have full control on your fields being returned or you can do it using JsonFilters as discussed in following links: 1. https://jira.spring.io/browse/SPR-12586 2. http://wiki.fasterxml.com/JacksonFeatureJsonFilter

@RequestMapping(method = RequestMethod.POST, value = "/springjsonfilter")
    public @ResponseBody MappingJacksonValue byJsonFilter(...) {
        MappingJacksonValue jacksonValue = new MappingJacksonValue(responseObj);    
        jacksonValue.setFilters(customFilterObj);
        return jacksonValue;
    }
于 2015-10-19T07:06:55.030 回答