使用jackson實(shí)現(xiàn)對(duì)象json之間的相互轉(zhuǎn)換(spring boot)
之前的json轉(zhuǎn)對(duì)象,對(duì)象轉(zhuǎn)json??偸潜容^繁瑣,不夠簡(jiǎn)潔。自從接觸到j(luò)ackson之后,發(fā)現(xiàn)原來(lái)對(duì)象和json轉(zhuǎn)換可以這么簡(jiǎn)單。拿一個(gè)天氣預(yù)報(bào)的小例子來(lái)說(shuō)明一下~如下圖。【若是有小誤,還望指正】

不說(shuō),直接上碼~
首先,在pom.xml里弄好依賴
具體依賴需要上網(wǎng)去查找,咱用的是下面這個(gè)。
<!-- 對(duì)象轉(zhuǎn)換成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>
然后嘞,準(zhǔn)備一個(gè)接口,
用來(lái)獲取天氣預(yù)報(bào)接口的數(shù)據(jù)
package com.lvfeng.tool.weather;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
/**
* @author LvFeng
* 來(lái)源:https://www.nowapi.com/
* 文檔:https://www.nowapi.com/api/weather.future
* 接口服務(wù)器【請(qǐng)求頭】:https://sapi.k780.com http://api.k780.com
* 每三個(gè)月一更新,需要定期更新
*/
public class WeatherAPI {
/*
* 00a.天氣預(yù)報(bào)接口
*/
public static final String APP_KEY_WEATHER = "你自己的key"; //KEY
public static final String SIGN_WEATHER = "你自己的sign"; //SIGN
/*
* 001.獲取一周的天氣
* @param 請(qǐng)求城市氣象編碼,請(qǐng)求APPKey,SignKey,返回?cái)?shù)據(jù)格式
* @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); //請(qǐng)求URL
InputStream ins = url.openStream(); //打開(kāi)輸入流
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"); //轉(zhuǎn)碼
}
}
插一嘴,簡(jiǎn)單粗暴的講,[]就是數(shù)組,{}就是對(duì)象,我們測(cè)試接口過(guò)后,
返回的json字符串就像下面這個(gè)樣子
/* {
* "success":"1",
* "result":[{
* "weaid":"1",
* "days":"2018-07-18",
* "week":"星期三",
* "cityno":"beijing",
* "citynm":"北京",
* "cityid":"101010100",
* "temperature":"32℃/25℃",
* "humidity":"0%/0%",
* "weather":"多云轉(zhuǎn)小雨",
* "weather_icon":"http://api.k780.com/upload/weather/d/1.gif",
* "weather_icon1":"http://api.k780.com/upload/weather/n/7.gif",
* "wind":"東風(fēng)",
* "winp":"<3級(jí)",
* "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"
* }, 這后面類(lèi)似……
*/
然后我們根據(jù)這構(gòu)建對(duì)象,根據(jù)這段json分析,這可能是倆對(duì)象,然后,一個(gè)對(duì)象是結(jié)果集數(shù)組[],一個(gè)對(duì)象是狀態(tài)(是否成功),于是,
我拆成了下面兩個(gè)對(duì)象
package com.lvfeng.tool.weather.pojo;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* @author Administrator
* 一周天氣對(duì)象
* 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; //結(jié)果集數(shù)組
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子類(lèi),天氣結(jié)果的返回值
*/
public class Result {
private String weaid; //本站【調(diào)用接口的這個(gè)站點(diǎn)】的城市ID編號(hào)
private String days; //日期
private String week; //周幾
private String cityno; //城市編碼
private String citynm; //城市名稱
private String cityid; //城市氣象ID【標(biāo)準(zhǔn)】
private String temperature; //氣溫
private String humidity; //濕度【暫未使用】
private String weather; //天氣
private String weather_icon; //白天的氣象圖標(biāo)
private String weather_icon1; //夜間的氣象圖標(biāo)
private String wind; //風(fēng)向
private String winp; //風(fēng)力
private String temp_high; //最高氣溫
private String temp_low; //最低氣溫
private String humi_high; //溫度欄位【棄用】
private String humi_low; //濕度欄位【棄用】
private String weatid; //白天天氣ID,可對(duì)照weather.wtype接口中weaid
private String weatid1; //夜間天氣ID,可對(duì)照weather.wtype接口中weaid
private String windid; //風(fēng)向ID(暫無(wú)對(duì)照表)
private String winpid; //風(fēng)力ID(暫無(wú)對(duì)照表)
private String weather_iconid; //氣象圖標(biāo)編號(hào)(白天),對(duì)應(yīng)weather_icon 1.gif
private String weather_iconid1; //氣象圖標(biāo)編號(hào)(夜間),對(duì)應(yīng)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;
}
}
開(kāi)始書(shū)寫(xiě)工具類(lèi),方便以后調(diào)用~
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轉(zhuǎn)換成對(duì)象
* @param:傳入對(duì)象,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.對(duì)象轉(zhuǎn)換成json
* @param:傳入對(duì)象
* @return:json字符串
*/
public static String objToJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
}
}
封裝完成,寫(xiě)測(cè)試類(lèi)
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("結(jié)果集" + res);
String res2 = WeatherAPI.getNowWeather("1", WeatherAPI.APP_KEY_WEATHER, WeatherAPI.SIGN_WEATHER, "json");
System.out.println("結(jié)果集2" + res2);
WeatherWeek wea = (WeatherWeek)JSONChange.jsonToObj(new WeatherWeek(), res);
System.out.println("是否成功?"+wea.getSuccess()+"結(jié)果集舉例【城市名稱】:"+wea.getResult().get(0).getCitynm());
System.out.println("---------------------開(kāi)始反轉(zhuǎn)------------------");
String jsonStr = JSONChange.objToJson(wea);
System.out.println("反轉(zhuǎn)結(jié)果:"+jsonStr);
}
}
如上,就把查詢天氣預(yù)報(bào)的結(jié)果轉(zhuǎn)換成倆對(duì)象了,然后我們操作對(duì)象~啦啦啦!
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Jackson使用示例-Bean、XML、Json之間相互轉(zhuǎn)換
- 一篇文章了解Jackson注解@JsonFormat及失效解決辦法
- Java中對(duì)象?和?json?互轉(zhuǎn)四種方式?json-lib、Gson、FastJson、Jackson
- 利用Jackson解決Json序列化和反序列化問(wèn)題
- Java利用Jackson輕松處理JSON序列化與反序列化
- Jackson中json格式的字符串與對(duì)象的互相轉(zhuǎn)換方式
- 如何自定義Jackson序列化?@JsonSerialize
- JSON中fastjson、jackson、gson如何選擇
- jackson 如何將實(shí)體轉(zhuǎn)json json字符串轉(zhuǎn)實(shí)體
- 使用Jackson-json解析一個(gè)嵌套的json字符串
- Jackson庫(kù)進(jìn)行JSON?序列化時(shí)遇到了無(wú)限遞歸(Infinite?Recursion)的問(wèn)題及解決方案
相關(guān)文章
Java.lang.Long.parseLong()方法詳解及示例
這個(gè)java.lang.Long.parseLong(String s) 方法解析字符串參數(shù)s作為有符號(hào)十進(jìn)制長(zhǎng),下面這篇文章主要給大家介紹了關(guān)于Java.lang.Long.parseLong()方法詳解及示例的相關(guān)資料,需要的朋友可以參考下2023-01-01
Spring cloud Feign 深度學(xué)習(xí)與應(yīng)用詳解
這篇文章主要介紹了Spring cloud Feign 深度學(xué)習(xí)與應(yīng)用詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
Java中parallelStream().forEach()的踩坑日記
本文主要介紹了Java中parallelStream().forEach()的踩坑日記,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
springboot整合x(chóng)xl-job實(shí)現(xiàn)分布式定時(shí)任務(wù)的過(guò)程
XXL-JOB是一個(gè)分布式任務(wù)調(diào)度平臺(tái),其核心設(shè)計(jì)目標(biāo)是開(kāi)發(fā)迅速、學(xué)習(xí)簡(jiǎn)單、輕量級(jí)、易擴(kuò)展,這篇文章主要介紹了springboot整合x(chóng)xl-job分布式定時(shí)任務(wù),需要的朋友可以參考下2022-08-08
Spring?Cloud?Stream實(shí)現(xiàn)數(shù)據(jù)流處理
Spring?Cloud?Stream的核心是Stream,準(zhǔn)確來(lái)講Spring?Cloud?Stream提供了一整套數(shù)據(jù)流走向(流向)的API,?它的最終目的是使我們不關(guān)心數(shù)據(jù)的流入和寫(xiě)出,而只關(guān)心對(duì)數(shù)據(jù)的業(yè)務(wù)處理,本文給大家介紹了Spring?Cloud?Stream實(shí)現(xiàn)數(shù)據(jù)流處理,需要的朋友可以參考下2024-11-11
Java中如何自定義一個(gè)類(lèi)加載器加載自己指定的類(lèi)
這篇文章主要給大家介紹了關(guān)于Java中如何自定義一個(gè)類(lèi)加載器加載自己指定的類(lèi),自定義類(lèi)加載器允許我們加載特定路徑的類(lèi)文件,并且可以用于插件系統(tǒng)、熱部署和隔離加載等場(chǎng)景,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-12-12
Arthas在線java進(jìn)程診斷工具在線調(diào)試神器詳解
Arthas是 Alibaba 開(kāi)源的Java診斷工具,深受開(kāi)發(fā)者喜愛(ài)。這篇文章主要介紹了Arthas在線java進(jìn)程診斷工具 在線調(diào)試神器,需要的朋友可以參考下2021-11-11

