1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSON

Posted at

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);

参考

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?