SQLの窓 イラストAC フリー素材

2012年09月24日

JSON.net の文字列から内容の参照のバターンサンプルがわりと全く無かったので作成

だいぶ前、VB.net で同じような事したんですが、だいぶ変わっていたし、全部見て無いですが、対象によって違うかもしれません。これは Windows Phone の C# です(Windows8 のC# でも動作しました)。

JSON データの整形は、http://winofsql.jp/php/cnvtext/frame.htm から、『JavaScript整形』で可能です。

※ DynamicJson は Windows Phone の環境で使えません。
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
// PropertyChangedEventHandler
using System.ComponentModel;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace PhoneApp1
{
	public class Class1 : INotifyPropertyChanged
	{
		public Class1(){

			WebClient webClient = new WebClient();

			webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
			// 外部サービスから文字列を取得
			webClient.DownloadStringAsync(new System.Uri("http://textt.net/sworc/20120924055943.txt"));
		}

		// ページ名プロパティ( バインド用 )
		public string pageName { get; set; }

		private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			if (e.Error != null)
			{
				Deployment.Current.Dispatcher.BeginInvoke(() =>
				{
					Debug.WriteLine(e.Error.Message);
				});
			}
			else
			{
				// オーソドックスなデシリアライズ
				Class2 JsonObject = JsonConvert.DeserializeObject<Class2>(e.Result);

				// 定義済のクラスとして参照( 未定義のプロパティは無視 )
				Debug.WriteLine(JsonObject.id);
				Debug.WriteLine(JsonObject.profile_background_image_url_https);

				// 文字列から JObject を作成
				JObject jo =  JObject.Parse(e.Result);

				// JObject で参照
				Debug.WriteLine(jo["id"]);
				Debug.WriteLine(jo["profile_background_image_url_https"]);

				// JToken で参照
				foreach (JToken jt in jo.Children())
				{
					Debug.WriteLine("-->" + jt.ToString());
					Debug.WriteLine("-->" + jt.First);
					
				}

				// JProperty で参照
				foreach (JProperty jp in jo.Properties())
				{
					Debug.WriteLine( jp.Name + "-->" + jp.Value.ToString());
				}

			}
		}

		public event PropertyChangedEventHandler PropertyChanged;
		public void NotifyPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this,
					new PropertyChangedEventArgs(propertyName));
			}
		}

	}
}


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace PhoneApp1
{
	public class Class2
	{
		public int id { get; set; }
		public string profile_background_image_url_https { get; set; }
	}
}




【C#の最新記事】
posted by at 2012-09-24 21:42 | C# | このブログの読者になる | 更新情報をチェックする