iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用jackson实现对象json之间的相互转换(spring boot)
  • 430
分享到

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

2024-04-02 19:04:59 430人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

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

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);
	}
}

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

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

--结束END--

本文标题: 使用jackson实现对象json之间的相互转换(spring boot)

本文链接: https://www.lsjlt.com/news/136062.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作