java解析json數據

1.背景

最近在解析json的數據,發現直接用HQL邏輯很繁瑣,於是藉助java,再添加爲UDF。

2.什麼是json(參考:http://www.json.org/)

json一共有兩種數據結構

(1)以(key/value)對形式存在的無序的jsonObject對象,其以"{"(左括號)開始,以"}"(右括號)結束。

格式如下:

{
"名稱1":"值1",
"名稱2":"值2",
"名稱3":"值3"	
}



名稱和值之間用":"(冒號)對應,不同名稱/值之間使用","(逗號)分隔。下面舉一個簡單的例子。

{
"name":"xiaoming",
"age":10,
"sex":"male"	
}



這就是一個最簡單的json對象,對於這種數據格式,key必須是string,value可以是string,number,object,array,true,false,null等等數據類型。

(2)有序的value集合,這種形式被稱爲jsonArray,數組是值(value)的有序集合。一個數組以“[”(左中括號)開始,“]”(右中括號)結束。值之間使用“,”(逗號)分隔。

{
	"employee":[
	{"name":"John","age":20,"sex":"男"},
	{"name":"Anna","age":25,"sex":"男"},
	{"name":"Peter","age":22,"sex":"男"}
	]
}



在上面的例子中,對象employee是包含三個對象的數組。每個對象包含某個員工的信息(姓名,年齡,性別)。

3.舉例

在這裏我們可以學到的是:

(1)區別JSONObject與JSONArray

(2)能夠解析json數據

下面是一個json文件:

{
    "resultcode": "200",
    "reason": "successed!",
    "result": {
        "sk": {
            "temp": "24",
            "wind_direction": "西南風",
            "wind_strength": "2級",
            "humidity": "51%",
            "time": "10:11"
        },
        "today": {
            "temperature": "16℃~27℃",
            "weather": "陰轉多雲",
            "weather_id": {
                "fa": "02",
                "fb": "01"
            },
            "wind": "西南風3-4 級",
            "week": "星期四",
            "city": "濱州",
            "date_y": "2015年06月04日",
            "dressing_index": "舒適",
            "dressing_advice": "建議着長袖T恤、襯衫加單褲等服裝。年老體弱者宜着針織長袖襯衫、馬甲和長褲。",
            "uv_index": "最弱",
            "comfort_index": "",
            "wash_index": "較適宜",
            "travel_index": "",
            "exercise_index": "較適宜",
            "drying_index": ""
        },
        "future": [
            {
                "temperature": "16℃~27℃",
                "weather": "陰轉多雲",
                "weather_id": {
                    "fa": "02",
                    "fb": "01"
                },
                "wind": "西南風3-4 級",
                "week": "星期四",
                "date": "20150604"
            },
            {
                "temperature": "20℃~32℃",
                "weather": "多雲轉晴",
                "weather_id": {
                    "fa": "01",
                    "fb": "00"
                },
                "wind": "西風3-4 級",
                "week": "星期五",
                "date": "20150605"
            },
            {
                "temperature": "23℃~35℃",
                "weather": "多雲轉陰",
                "weather_id": {
                    "fa": "01",
                    "fb": "02"
                },
                "wind": "西南風3-4 級",
                "week": "星期六",
                "date": "20150606"
            },
            {
                "temperature": "20℃~33℃",
                "weather": "多雲",
                "weather_id": {
                    "fa": "01",
                    "fb": "01"
                },
                "wind": "北風微風",
                "week": "星期日",
                "date": "20150607"
            },
            {
                "temperature": "22℃~34℃",
                "weather": "多雲",
                "weather_id": {
                    "fa": "01",
                    "fb": "01"
                },
                "wind": "西南風3-4 級",
                "week": "星期一",
                "date": "20150608"
            },
            {
                "temperature": "22℃~33℃",
                "weather": "陰",
                "weather_id": {
                    "fa": "02",
                    "fb": "02"
                },
                "wind": "西南風3-4 級",
                "week": "星期二",
                "date": "20150609"
            },
            {
                "temperature": "22℃~33℃",
                "weather": "多雲",
                "weather_id": {
                    "fa": "01",
                    "fb": "01"
                },
                "wind": "南風3-4 級",
                "week": "星期三",
                "date": "20150610"
            }
        ]
    },
    "error_code": 0
}



我們進行解析:
package com.exercise;

import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class Analyse_json {

	public static void main(String args[]) {

		String Path = "E:/WorkSpaces/test.json";
		JsonParser parser = new JsonParser();// 創建json解析器
		try {
			// 創建JsonObject對象
			JsonObject object = (JsonObject) parser.parse(new FileReader(Path));
			// 將json數據轉爲int型的數據
			System.out.println("resultcode:" + object.get("resultcode").getAsInt());
			// 將json數據轉爲String型的數據
			System.out.println("reason:" + object.get("reason").getAsString());

			JsonObject result = object.get("result").getAsJsonObject();
			JsonObject today = result.get("today").getAsJsonObject();
			System.out.println("\n今天的天氣情況");
			System.out.println("temperature:" + today.get("temperature").getAsString());
			System.out.println("weather:" + today.get("weather").getAsString());

			// 得到爲json的數組

			JsonArray array = result.get("future").getAsJsonArray();
			System.out.println("\n未來幾天的天氣情況");
			for (int i = 0; i < array.size(); i++) {

				System.out.println("-----------------------");
				JsonObject subObject = array.get(i).getAsJsonObject();
				System.out.println("temperature:" + subObject.get("temperature").getAsString());
				System.out.println("weather:" + subObject.get("weather").getAsString());
				System.out.println("wind:" + subObject.get("wind").getAsString());
				System.out.println("date:" + subObject.get("date").getAsString());

			}

		} catch (JsonIOException e) {
			e.printStackTrace();
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

}


輸出結果:

resultcode:200
reason:successed!


今天的天氣情況
temperature:16℃~27℃
weather:陰轉多雲


未來幾天的天氣情況
-----------------------
temperature:16℃~27℃
weather:陰轉多雲
wind:西南風3-4 級
date:20150604
-----------------------
temperature:20℃~32℃
weather:多雲轉晴
wind:西風3-4 級
date:20150605
-----------------------
temperature:23℃~35℃
weather:多雲轉陰
wind:西南風3-4 級
date:20150606
-----------------------
temperature:20℃~33℃
weather:多雲
wind:北風微風
date:20150607
-----------------------
temperature:22℃~34℃
weather:多雲
wind:西南風3-4 級
date:20150608
-----------------------
temperature:22℃~33℃
weather:陰
wind:西南風3-4 級
date:20150609
-----------------------
temperature:22℃~33℃
weather:多雲
wind:南風3-4 級
date:20150610

我們對上面進行解釋:
1.首先創建JsonObject對象object,相對其來講resultcode,reason,result,error_code是並列的。這是很明顯的
JsonObject
2.對於result對象來說,sk,today,future是並列的。這是很明顯的JsonObject
3.剖析future來講,這是一個JSONArray,如果想要解析裏面的信息,需要先get json數組。通過
JsonArray array = result.get("future").getAsJsonArray();實現
分析:
我們通過Gson進行解析,所以在使用前導入Gson.jar
(pom如下:
 <dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.7</version>
		</dependency>
)
解析json數據時,
1.需要進行創建Gson解析器
2.創建JsonObject對象
3.將json數據轉爲相應的數據

4.參考
博客
http://www.cnblogs.com/boy1025/p/4551593.html
http://www.cnblogs.com/xiaoluo501395377/p/3446605.html









































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章