[.NET]利用JSON.NET剖析巢狀NESTED JSON字串裡的陣列

  • 2290
  • 0
  • 2016-03-16

[.NET]利用JSON.NET剖析巢狀NESTED JSON字串裡的陣列

首先先去下載JSON.NET套件:
http://www.newtonsoft.com/json
不過你可以選擇直接下載,或是nuget執行commandline直接安裝

.json內容就以最近的土壤液化open data為例子:
可以到經濟部中央地質調查所http://www.geologycloud.tw/map/liquefaction/zh-tw下載土壤液化open data,並利用http://www.jsoneditoronline.org/察看json剖析後的結果的話:
可以發現巢狀的內容在features=>geometry=>coordinates裡面,內有多筆經緯度座標。

接下來只要使用三次(JObject.Parse(open data的json的字串) + foreach),就可以解析出巢狀的json內容囉:
本篇以Winform為例。

private void button1_Click(object sender, EventArgs e)
{
	string jsonFileName = @"D:\\temp\\liquefaction.json";
	string jsonFileContent = System.IO.File.ReadAllText(jsonFileName);
	JObject fileContentObj = JObject.Parse(jsonFileContent);            
	//取得所有features下面的children
	IList<JToken> features = fileContentObj["features"].Children().ToList();
	int i = 0;
	foreach (JToken f in features)
	{                
		string featureJson = "";
		featureJson = f.ToString();
		JObject CoordinatesObj = JObject.Parse(featureJson);
		IList<JToken> coordinates = CoordinatesObj["geometry"]["coordinates"].Children().ToList();
		foreach (JToken c in coordinates)
		{                    
			textBox1.Text += "第" + i.ToString() + "筆資料:" + "\r\n";
			textBox1.Text += c.ToString() + "\r\n";
		}
		i++;

		//僅作示範因此只跑兩次迴圈喔
		if(i== 2)
		break;
	}            
}

執行結果:
成功取出兩組coordinates經緯度座標資料:

非巢狀的json的解析就是使用一次(JObject.Parse(open data的json的字串) + foreach)就可以解決囉~這應該不用示範了。。。

這篇大概是這樣。。。

參考資料:
Deserializing Partial JSON Fragments
http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm