栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 官方文档示例:(45)spring boot 对json的支持

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

SpringBoot 官方文档示例:(45)spring boot 对json的支持

一、Spring boot默认集成了3种json映射库的支持:
Gson
Jackson
JSON-B
其中默认的是Jackson
二、Spring boot 默认自动配置了类型为ObjectMapper(该类型来自于Jackson)的bean.可以直接使用该bean进行json映射。
如果pom.xml中配置了gson依赖,则spring boot会自动装配一个类型为Gson的bean.

        
            com.google.code.gson
            gson
            2.8.6
        

三、上述两个bean的简单使用:

package cn.edu.tju.controller;

import cn.edu.tju.domain.UserInfo;
import cn.edu.tju.service.BasicService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController3 {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    Gson gson;

    @RequestMapping("/test1")
    public String getMessage() throws Exception{
        Map map=new HashMap<>();
        map.put("username","amadeus");
        map.put("password","liu");
        String result=objectMapper.writeValueAsString(map);
        return result;
    }

    @RequestMapping("/test2")
    public String getMessage2() throws Exception{
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername("paul");
        userInfo.setPassword("schools");
        String result=gson.toJson(userInfo);
        return result;
    }
}

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

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

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