使用jackson实现对象json之间的相互转换(spring boot)

目录
  • 首先,在pom.xml里弄好依赖
  • 用来获取天气预报接口的数据
  • 返回的json字符串就像下面这个样子
  • 我拆成了下面两个对象
  • 开始书写工具类,方便以后调用~
  • 封装完成,写测试类

之前的json转对象,对象转json。总是比较繁琐,不够简洁。自从接触到jackson之后,发现原来对象和json转换可以这么简单。拿一个天气预报的小例子来说明一下~如下图。【若是有小误,还望指正】

不说,直接上码~

首先,在pom.xml里弄好依赖

具体依赖需要上网去查找,咱用的是下面这个。

		<!-- 对象转换成json引入如下依赖 -->
		<!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
		<dependency>
    		<groupId>com.fasterxml.jackson.core</groupId>
    		<artifactId>jackson-databind</artifactId>
    		<version>2.7.4</version>
		</dependency>

然后嘞,准备一个接口,

用来获取天气预报接口的数据

package com.lvfeng.tool.weather;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @author LvFeng
 * 来源:https://www.nowapi.com/
 * 文档:https://www.nowapi.com/api/weather.future
 * 接口服务器【请求头】:https://sapi.k780.com   http://api.k780.com
 * 每三个月一更新,需要定期更新
 */
public class WeatherAPI {
	/*
	 * 00a.天气预报接口
	 */
	public static final String APP_KEY_WEATHER = "你自己的key";	//KEY
	public static final String SIGN_WEATHER = "你自己的sign";	//SIGN
	/*
	 * 001.获取一周的天气
	 * @param 请求城市气象编码,请求APPKey,SignKey,返回数据格式
	 * @return JSON
	 * DOC:https://www.nowapi.com/api/weather.future
	 * FORMAT:http://api.k780.com/?app=weather.future&weaid=1&appkey=APPKEY&sign=SIGN&format=json
	 */
	public static String getWeatherWeek(String cityNumber,String ak,String sg,String returnFormat) throws Exception{
		String str = "http://api.k780.com/?app=weather.future&weaid="+cityNumber+"&appkey="+ak+"&sign="+sg+"&format="+returnFormat;
		URL url = new URL(str);	//请求URL
		InputStream ins = url.openStream();	//打开输入流
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
            byte buf[] = new byte[1024];
            int read = 0;
            while ((read = ins.read(buf)) > 0) {
                out.write(buf, 0, read);
            }
        } finally {
            if (ins != null) {
                ins.close();
            }
        }
        byte b[] = out.toByteArray( );
		return new String(b,"utf-8");	//转码
	}
}

插一嘴,简单粗暴的讲,[]就是数组,{}就是对象,我们测试接口过后,

返回的json字符串就像下面这个样子

		/* {
		 * "success":"1",
		 * "result":[{
		 * 		"weaid":"1",
		 * 		"days":"2018-07-18",
		 * 		"week":"星期三",
		 * 		"cityno":"beijing",
		 * 		"citynm":"北京",
		 * 		"cityid":"101010100",
		 * 		"temperature":"32℃/25℃",
		 * 		"humidity":"0%/0%",
		 * 		"weather":"多云转小雨",
		 * 		"weather_icon":"http://api.k780.com/upload/weather/d/1.gif",
		 * 		"weather_icon1":"http://api.k780.com/upload/weather/n/7.gif",
		 * 		"wind":"东风",
		 * 		"winp":"<3级",
		 * 		"temp_high":"32",
		 * 		"temp_low":"25",
		 * 		"humi_high":"0",
		 * 		"humi_low":"0",
		 * 		"weatid":"2",
		 * 		"weatid1":"8",
		 * 		"windid":"10",
		 * 		"winpid":"395",
		 * 		"weather_iconid":"1",
		 * 		"weather_iconid1":"7"
		 * 	}, 这后面类似……
		 */

然后我们根据这构建对象,根据这段json分析,这可能是俩对象,然后,一个对象是结果集数组[],一个对象是状态(是否成功),于是,

我拆成了下面两个对象

package com.lvfeng.tool.weather.pojo;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

/**
 * @author Administrator
 * 一周天气对象
 * DOC:https://blog.csdn.net/u010457406/article/details/50921632
 * 	   https://blog.csdn.net/jxchallenger/article/details/79293772
 */
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property ="success")
public class WeatherWeek {
	private String success;	//是否成功
	private List<Result> result;	//结果集数组

	public String getSuccess() {
		return success;
	}
	public void setSuccess(String success) {
		this.success = success;
	}
	public List<Result> getResult() {
		return result;
	}
	public void setResult(List<Result> result) {
		this.result = result;
	}
}
package com.lvfeng.tool.weather.pojo;
/**
 * @author LvLvFeng
 * Weather子类,天气结果的返回值
 */
public class Result {
	private String weaid;	//本站【调用接口的这个站点】的城市ID编号
	private String days;	//日期
	private String week;	//周几
	private String cityno;	//城市编码
	private String citynm;	//城市名称
	private String cityid;	//城市气象ID【标准】
	private String temperature;	//气温
	private String humidity;	//湿度【暂未使用】
	private String weather;		//天气
	private String weather_icon;	//白天的气象图标
	private String weather_icon1;	//夜间的气象图标
	private String wind;			//风向
	private String winp;			//风力
	private String temp_high;		//最高气温
	private String temp_low;		//最低气温
	private String humi_high;		//温度栏位【弃用】
	private String humi_low;		//湿度栏位【弃用】
	private String weatid;			//白天天气ID,可对照weather.wtype接口中weaid
	private String weatid1;			//夜间天气ID,可对照weather.wtype接口中weaid
	private String windid;			//风向ID(暂无对照表)
	private String winpid;			//风力ID(暂无对照表)
	private String weather_iconid;	//气象图标编号(白天),对应weather_icon 1.gif
	private String weather_iconid1;	//气象图标编号(夜间),对应weather_icon1 0.gif
	public String getWeaid() {
		return weaid;
	}
	public void setWeaid(String weaid) {
		this.weaid = weaid;
	}
	public String getDays() {
		return days;
	}
	public void setDays(String days) {
		this.days = days;
	}
	public String getWeek() {
		return week;
	}
	public void setWeek(String week) {
		this.week = week;
	}
	public String getCityno() {
		return cityno;
	}
	public void setCityno(String cityno) {
		this.cityno = cityno;
	}
	public String getCitynm() {
		return citynm;
	}
	public void setCitynm(String citynm) {
		this.citynm = citynm;
	}
	public String getCityid() {
		return cityid;
	}
	public void setCityid(String cityid) {
		this.cityid = cityid;
	}
	public String getTemperature() {
		return temperature;
	}
	public void setTemperature(String temperature) {
		this.temperature = temperature;
	}
	public String getHumidity() {
		return humidity;
	}
	public void setHumidity(String humidity) {
		this.humidity = humidity;
	}
	public String getWeather() {
		return weather;
	}
	public void setWeather(String weather) {
		this.weather = weather;
	}
	public String getWeather_icon() {
		return weather_icon;
	}
	public void setWeather_icon(String weather_icon) {
		this.weather_icon = weather_icon;
	}
	public String getWeather_icon1() {
		return weather_icon1;
	}
	public void setWeather_icon1(String weather_icon1) {
		this.weather_icon1 = weather_icon1;
	}
	public String getWind() {
		return wind;
	}
	public void setWind(String wind) {
		this.wind = wind;
	}
	public String getWinp() {
		return winp;
	}
	public void setWinp(String winp) {
		this.winp = winp;
	}
	public String getTemp_high() {
		return temp_high;
	}
	public void setTemp_high(String temp_high) {
		this.temp_high = temp_high;
	}
	public String getTemp_low() {
		return temp_low;
	}
	public void setTemp_low(String temp_low) {
		this.temp_low = temp_low;
	}
	public String getHumi_high() {
		return humi_high;
	}
	public void setHumi_high(String humi_high) {
		this.humi_high = humi_high;
	}
	public String getHumi_low() {
		return humi_low;
	}
	public void setHumi_low(String humi_low) {
		this.humi_low = humi_low;
	}
	public String getWeatid() {
		return weatid;
	}
	public void setWeatid(String weatid) {
		this.weatid = weatid;
	}
	public String getWeatid1() {
		return weatid1;
	}
	public void setWeatid1(String weatid1) {
		this.weatid1 = weatid1;
	}
	public String getWindid() {
		return windid;
	}
	public void setWindid(String windid) {
		this.windid = windid;
	}
	public String getWinpid() {
		return winpid;
	}
	public void setWinpid(String winpid) {
		this.winpid = winpid;
	}
	public String getWeather_iconid() {
		return weather_iconid;
	}
	public void setWeather_iconid(String weather_iconid) {
		this.weather_iconid = weather_iconid;
	}
	public String getWeather_iconid1() {
		return weather_iconid1;
	}
	public void setWeather_iconid1(String weather_iconid1) {
		this.weather_iconid1 = weather_iconid1;
	}
}

开始书写工具类,方便以后调用~

package com.lvfeng.tool.change;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author LvLvFeng
 * 操作json的封装方法
 * use:jackson
 */
public class JSONChange {
	/*
	 * 001.json转换成对象
	 * @param:传入对象,json字符串
	 * @return:Object
	 */
	public static Object jsonToObj(Object obj,String jsonStr) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
	    return obj = mapper.readValue(jsonStr, obj.getClass());
	}
	/*
	 * 002.对象转换成json
	 * @param:传入对象
	 * @return:json字符串
	 */
	public static String objToJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}
}

封装完成,写测试类

package com.lvfeng.tool.weather;
import com.lvfeng.tool.change.JSONChange;
import com.lvfeng.tool.weather.pojo.WeatherWeek;
public class TestWeather {
	public static void main(String[] args) throws Exception{
		//城市列表,ak,sg,返回格式
		String res = WeatherAPI.getWeatherWeek("1", WeatherAPI.APP_KEY_WEATHER, WeatherAPI.SIGN_WEATHER, "json");
		System.out.println("结果集" + res);
		String res2 = WeatherAPI.getNowWeather("1", WeatherAPI.APP_KEY_WEATHER, WeatherAPI.SIGN_WEATHER, "json");
		System.out.println("结果集2" + res2);
		WeatherWeek wea = (WeatherWeek)JSONChange.jsonToObj(new WeatherWeek(), res);
		System.out.println("是否成功?"+wea.getSuccess()+"结果集举例【城市名称】:"+wea.getResult().get(0).getCitynm());
		System.out.println("---------------------开始反转------------------");
		String jsonStr = JSONChange.objToJson(wea);
		System.out.println("反转结果:"+jsonStr);
	}
}

如上,就把查询天气预报的结果转换成俩对象了,然后我们操作对象~啦啦啦!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 使用Jackson来实现Java对象与JSON的相互转换的教程

    一.入门 Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换. 1.JAVA对象转JSON[JSON序列化] import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonDemo { p

  • 详解json在SpringBoot中的格式转换

    @RestController自动返回json /** * json 三种实现方法 * 1 @RestController自动返回json */ @GetMapping("/json") public Student getjson() { Student student = new Student("bennyrhys",158 ); return student; } @ResponseBody+@Controller 组合返回json //@RestContr

  • java jackson 将对象转json时,忽略子对象的某个属性操作

    我就废话不多说了,大家还是直接看代码吧~ //父对象 public class user implements java.io.Serializable { @JsonIgnoreProperties(value={"addressId"})//在解析成json时,忽略子属性的addressId字段 private Address address; private String username; //......... } //子对象 public class Address imp

  • Java实现Json字符串与Object对象相互转换的方式总结

    本文实例总结了Java实现Json字符串与Object对象相互转换的方式.分享给大家供大家参考,具体如下: Json-Lib.Org.Json.Jackson.Gson.FastJson五种方式转换json类型 只列举了最省事的方式.不涉及复制情况和速度. 测试用例,一个User类,属性name,age,location.重写toString(). public class User { private String name; private Integer age; private Stri

  • 使用spring boot开发时java对象和Json对象转换的问题

    将java对象转换为json对象,市面上有很多第三方jar包,如下: jackson(最常用) <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind&l

  • 使用jackson实现对象json之间的相互转换(spring boot)

    目录 首先,在pom.xml里弄好依赖 用来获取天气预报接口的数据 返回的json字符串就像下面这个样子 我拆成了下面两个对象 开始书写工具类,方便以后调用~ 封装完成,写测试类 之前的json转对象,对象转json.总是比较繁琐,不够简洁.自从接触到jackson之后,发现原来对象和json转换可以这么简单.拿一个天气预报的小例子来说明一下~如下图.[若是有小误,还望指正] 不说,直接上码~ 首先,在pom.xml里弄好依赖 具体依赖需要上网去查找,咱用的是下面这个. <!-- 对象转换成js

  • C#实现String类型和json之间的相互转换功能示例

    本文实例讲述了C#实现String类型和json之间的相互转换功能.分享给大家供大家参考,具体如下: ////Donet2.0 需要添加引用 // 从一个对象信息生成Json串 public static string ObjectToJson(object obj) { return JavaScriptConvert.SerializeObject(obj); } // 从一个Json串生成对象信息 public static object JsonToObject(string jsonS

  • java实现Xml与json之间的相互转换操作示例

    本文实例讲述了java实现Xml与json之间的相互转换操作.分享给大家供大家参考,具体如下: 旁白: 最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用. 正题: project格式是: jar包是一个一个检出来的,还算干净了. 代码: 工具类: package exercise.xml; import net.sf.json.JSON; import net.sf.json.JSONSerializer; import net.sf.json.xml.XMLSerial

  • php实现xml与json之间的相互转换功能实例

    本文实例讲述了php实现xml与json之间的相互转换功能.分享给大家供大家参考,具体如下: 用php实现xml与json之间的相互转换: 相关函数请查看php手册. 一.参考xml如下 <?xml version="1.0" encoding="UTF-8"?> <humans> <zhangying> <name>张三</name> <sex>男</sex> <old>

  • golang struct, map, json之间的相互转换

    本文用于记录我在 golang 学习阶段遇到的类型转换问题,针对的是 json .map.struct 之间相互转换的问题,用到的技术 json .mapstructure.reflect 三个类库 公共代码区域 package main import ( "encoding/json" "fmt" "testing" ) type UserInfoVo struct { Id string `json:"id"` UserN

  • Spring Boot中如何使用Convert接口实现类型转换器

    目录 使用Convert接口实现类型转换器 Converter接口 添加依赖 实体类 1.User类 2.Article类 配置类型转化器 1.定义全局日期转换器 2.定义全局对象转换器 3.定义全局List类型转换器 控制器 测试 Converter使用及其原理 配置文件中对Converter的引用 以字符串去空为例 我们查看Converter接口的源码 我们查看对应的成员变量: 使用Convert接口实现类型转换器 在Spring3中引入了一个Converter接口,它支持从一个Object

  • Spring Boot XSS 攻击过滤插件使用

    XSS 是什么 XSS(Cross Site Scripting)攻击全称跨站脚本攻击,为了不与 CSS(Cascading Style Sheets)名词混淆,故将跨站脚本攻击简称为 XSS,XSS 是一种常见 web 安全漏洞,它允许恶意代码植入到提供给其它用户使用的页面中. xss 攻击流程 简单 xss 攻击示例若网站某个表单没做相关的处理,用户提交相关恶意代码,浏览器会执行相关的代码. 解决方案 XSS 过滤说明 对表单绑定的字符串类型进行 xss 处理. 对 json 字符串数据进行

  • Spring Boot 注解方式自定义Endpoint详解

    目录 概述 准备 编写自定义Endpoint 配置 启动&测试 注意 Spring Boot 常用endpoint的使用 Actuator 一些常用 Endpoint 如何访问 Actuator Endpoint 概述 在使用Spring Boot的时候我们经常使用actuator,健康检查,bus中使用/refresh等.这里记录如何使用注解的方式自定义Endpoint.可用于满足一些服务状态监控,或者优雅停机等. 准备 Spring Boot项目,pom中加入: <dependency&

  • FastJson对于JSON格式字符串、JSON对象及JavaBean之间的相互转换操作

    fastJson对于json格式字符串的解析主要用到了一下三个类: JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换. JSONObject:fastJson提供的json对象. JSONArray:fastJson提供json数组对象. 我们可以把JSONObject当成一个Map<String,Object>来看,只是JSONObject提供了更为丰富便捷的方法,方便我们对于对象属性的操作.我们看一下源码. 同样我们可以把JSONArra

随机推荐