19
20

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.

C# + LINQ でJSONのパースをする

Posted at

今回はWindowsPhoneです。

JSON.netを利用します。解析対象はFoursquareのexploreAPI。

レスポンスのJSONの内、Venueのみを抽出します。

結論から言うと、シリアライズした方が楽。

まずは結果を保存するvenue.cs

venue.cs
namespace ConflimJsonParser
{
    public class Venue
    {
        public string name { get; set; }
        public string address { get; set; }
        public string crossStreet { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string country { get; set; }
        public string cc { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
        public string id { get; set; }
    }
}

そして、実際に解析を行うMyParser.cs

MyParser.cs
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Diagnostics;

namespace ConflimJsonParser
{
    public class MyParser
    {
        private string json = "省略";

        public void parse()
        {
            var str = JObject.Parse(json).SelectToken("response.groups").ToString();
            var venues = JArray.Parse(str).SelectMany(groups => groups["items"])
                .Select(items => items["venue"]).Select(venue =>
                {
                    var location = venue["location"];
                    return new Venue()
                    {
                        name = (string)venue["name"],
                        id = (string)venue["id"],
                        address = (string)location["address"],
                        crossStreet = (string)location["crossStreet"],
                        city = (string)location["city"],
                        state = (string)location["state"],
                        country = (string)location["country"],
                        cc = (string)location["cc"],
                        lat = (double)location["lat"],
                        lng = (double)location["lng"],
                    };
                });

            foreach (var venue in venues)
            {
                Debug.WriteLine(venue.name);

            }

        }

    }
}

同じ事をAndroidのJsonObjectとかを使ってやろうとすると、
forやifの鬼ネストになるんだろうな。

そういう意味では、すっきりしていてLINQは好きです。

好きだけど、やっぱりパーツの再利用が上手くできないというか何というか。

その辺上手く書けるようになりたいものですね。

19
20
2

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
19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?