一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 使用jackson實現對象json之間的相互轉換(spring boot)

使用jackson實現對象json之間的相互轉換(spring boot)

2022-01-07 13:15綠綠峰 Java教程

這篇文章主要介紹了使用jackson實現對象json之間的相互轉換(spring boot),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

之前的json轉對象,對象轉json??偸潜容^繁瑣,不夠簡潔。自從接觸到jackson之后,發現原來對象和json轉換可以這么簡單。拿一個天氣預報的小例子來說明一下~如下圖?!救羰怯行≌`,還望指正】

使用jackson實現對象json之間的相互轉換(spring boot)

不說,直接上碼~

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

具體依賴需要上網去查找,咱用的是下面這個。

?
1
2
3
4
5
6
7
<!-- 對象轉換成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>

然后嘞,準備一個接口,

用來獲取天氣預報接口的數據

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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字符串就像下面這個樣子

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* {
 * "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分析,這可能是倆對象,然后,一個對象是結果集數組[],一個對象是狀態(是否成功),于是,

我拆成了下面兩個對象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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;
    }  
}

開始書寫工具類,方便以后調用~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
    }
}

封裝完成,寫測試類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
    }
}

如上,就把查詢天氣預報的結果轉換成倆對象了,然后我們操作對象~啦啦啦!

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/qq_37525899/article/details/81132069

延伸 · 閱讀

精彩推薦
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發現了對于集合操作轉換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關于Java8中S...

    阿杜7482021-02-04
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經有好久沒有升過級了。升級完畢重啟之后,突然發現好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java實現搶紅包功能

    Java實現搶紅包功能

    這篇文章主要為大家詳細介紹了Java實現搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java BufferWriter寫文件寫不進去或缺失數據的解決

    Java BufferWriter寫文件寫不進去或缺失數據的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進去或缺失數據的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關于小米推送Java代碼,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩中求8032021-07-12
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程xml與Java對象的轉換詳解

    xml與Java對象的轉換詳解

    這篇文章主要介紹了xml與Java對象的轉換詳解的相關資料,需要的朋友可以參考下...

    Java教程網2942020-09-17
主站蜘蛛池模板: 亚洲成av人片在线观看天堂无码 | 男人好大好硬好爽免费视频 | 亚洲成aⅴ人片在线 | 91好色 | 鄂州一家三口完整版免费 | 99re免费在线视频 | 男人的天堂久久精品激情a 男人的天堂va | 成人国产精品 | 好涨好大我快受不了了视频网 | 免费看隐私美女 | 鄂州一家三口完整版免费 | 好涨好大我快受不了了视频网 | 涩色网站 | 日本女人www| 男男gaygays国内 | 亚洲日本久久一区二区va | 欧美伦理影院 | 久久电影精品久久99久久 | 久久中文字幕综合不卡一二区 | 国产成人v爽在线免播放观看 | 第一次做m被调教经历 | 睡男神的这件小事小说在线阅读 | 色综七七久久成人影 | 91免费播放人人爽人人快乐 | 亚洲haose在线观看 | 亚洲欧美国产在线 | 国产卡一卡二卡三乱码手机 | 操大姨子逼 | 日日草视频 | 亚洲成综合人影院在院播放 | 午夜国产精品影院在线观看 | 亚洲久草 | 果冻传媒在线播放观看228集 | 亚洲欧美激情日韩在线 | 高清不卡免费一区二区三区 | 久久精品国产久精国产果冻传媒 | 国产欧美日韩精品一区二 | 精品国产一区二区三区久 | 思敏1一5集国语版免费观看 | 日本动漫打扑克动画片樱花动漫 | 亚洲精品国产SUV |