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

编辑: admin 分类: java 发布时间: 2021-12-03 来源:互联网
目录
  • 首先,在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);
	}
}

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

【本文出处:国外高防服务器 复制请保留原URL】