Posted at

JSON

More than 1 year has passed since last update.

Newtonsoft の JSON.NET を使って、シリアライズ / デシリアライズを行う。


シリアライズ

var book = new Book()

{
Id = 1,
Title = "hello, world."
};

using (var stream = new StreamWriter("book.json"))
using (var writer = new JsonTextWriter(stream))
{
JsonSerializer serializer = new JsonSerializer()
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
serializer.Serialize(writer, book);
}


デシリアライズ

using (var stream = new StreamReader("book.json"))

using (var reader = new JsonTextReader(stream))
{
JsonSerializer serializer = new JsonSerializer() {
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var book = serializer.Deserialize<Book>(reader);
System.Diagnostics.Debug.WriteLine(book);
}


天気予報 (JSON) の取得

var wc = new WebClient();

wc.QueryString = new NameValueCollection()
{
// yokohama
["city"] = 140010.ToString()
};
wc.Encoding = Encoding.UTF8;

var result = wc.DownloadString(@"http://weather.livedoor.com/forecast/webservice/json/v1");

JObject o = JObject.Parse(result);

List<string> forecasts = o["forecasts"].Select(i => i["telop"].ToString()).ToList();

foreach(var f in forecasts)
{
System.Diagnostics.Debug.WriteLine(f);
}

//object json = JsonConvert.DeserializeObject(result);
//System.Diagnostics.Debug.WriteLine(json);


参考