文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

之前的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;
 

public class WeatherAPI {
	
	public static final String APP_KEY_WEATHER = "你自己的key";	//KEY
	public static final String SIGN_WEATHER = "你自己的sign";	//SIGN
	
	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字符串就像下面这个样子


		

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

我拆成了下面两个对象


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

@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;

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;
 

public class JSONChange {
	
	public static Object jsonToObj(Object obj,String jsonStr) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();	
	    return obj = mapper.readValue(jsonStr, obj.getClass());
	}
	
	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);
	}
}

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

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯