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

将Spring MVC投影与JSON和Jackson结合使用

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

将Spring MVC投影与JSON和Jackson结合使用

您可以使用Jackson Mr Bean模块,该模块正是您想要的。

要使用它,只需下载特定的依赖项并将其设置为基础

ObjectMapper
实例的模块即可:

import java.io.IOException;import java.util.List;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.module.mrbean.MrBeanModule;public class AbstractPojosExample {    public interface Person {        String getName();        int getAge();        Address getAddress();        default String asString() { return String.format("%s, %d, %s", this.getName(), this.getAge(), this.getAddress().asString());        }    }    public interface Address {        String getStreet();        String getCity();        default String asString() { return String.format("%s, %s", this.getStreet(), this.getCity());        }    }    private void run() throws IOException {        ObjectMapper mapper = new ObjectMapper();        mapper.registerModule(new MrBeanModule());        String json = "[ { "name": "John", "age": 23, " + ""address": { "street": "1001 5th Ave", "city": "New York" } }, " + "{ "name": "Jean Jacques", "age": 26 , " + ""address": { "street": "1001 Champs Elysees Blvd", "city": "Paris" } }, " + "{ "name": "Oscar Ruben", "age": 54, " + ""address": { "street": "1001 9th July Ave", "city": "Buenos Aires" } } ]";        System.out.println(json);        List<Person> people = mapper.readValue(json, new TypeReference<List<Person>>() {});        people.stream().map(Person::asString).forEach(System.out::println);    }    public static void main(String[] args) throws IOException {        AbstractPojosExample example = new AbstractPojosExample();        example.run();    }}

对于给定的json:

[  {    "name": "John",    "age": 23,    "address": {      "street": "1001 5th Ave",      "city": "New York"    }  },  {    "name": "Jean Jacques",    "age": 26,    "address": {      "street": "1001 Champs Elysees Blvd",      "city": "Paris"    }  },  {    "name": "Oscar Ruben",    "age": 54,    "address": {      "street": "1001 9th July Ave",      "city": "Buenos Aires"    }  }]

上面的小程序产生以下输出:

John, 23, 1001 5th Ave, New YorkJean Jacques, 26, 1001 Champs Elysees Blvd, ParisOscar Ruben, 54, 1001 9th July Ave, Buenos Aires


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

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

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