栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从json响应中动态删除字段?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从json响应中动态删除字段?

我也在为此要求而苦苦挣扎。

以下代码是使用@beerbajay在对问题的评论中已经提到的JsonViews的变通方法:

http://wiki.fasterxml.com/JacksonJsonViews

我正在使用Spring Boot 1.2.3。

Views.java

package demo;public class Views {    static interface Public {}    static interface Internal extends Public {}}

相册.java

package demo;import com.fasterxml.jackson.annotation.JsonView;public class Album {    @JsonView(Views.Public.class)    private String id;    @JsonView(Views.Public.class)    private String title;    @JsonView(Views.Public.class)    private String artist;    @JsonView(Views.Internal.class)    private String secret;    public Album(String id, String title, String artist, String secret) {        this.id = id;        this.title = title;        this.artist = artist;        this.secret = secret;    }}

AlbumController.java

package demo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.ObjectWriter;@RestControllerpublic class AlbumController {    @Autowired    ObjectMapper mapper;    @RequestMapping(value = "/album", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)    public String getAlbum() throws JsonProcessingException {        Album foo = new Album("1", "foo", "John Doe", "secretProperty");        // replace the following value with runtime logic of your choice,        // e.g. role of a user        boolean forInternal = false;        ObjectWriter viewWriter;        if (forInternal) { viewWriter = mapper.writerWithView(Views.Internal.class);        } else { viewWriter = mapper.writerWithView(Views.Public.class);        }        return viewWriter.writevalueAsString(foo);    }}

因此,关键是使用杰克逊的ObjectMapper和ObjectWriter生成对象的json表示形式的
字符串

对我来说有点丑陋,但是有效。当然,问题仍然在于定义多个时如何缩放

RequestMapping



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428409.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号