본문 바로가기
C++ 200제/코딩 IT 정보

[C# JSON] LINQ JSON 쿼리 제어 3가지 방법

by vicddory 2017. 8. 22.

[C# JSON] LINQ JSON 쿼리 제어 3가지 방법


C# LINQ는 C# JSON 객체에서 데이터를 가져오는 여러 가지 방법을 제공합니다. JObject, jArray 함수를 활용하면 속성별로 빠르게 데이터를 가져올 수 있습니다. 이 포스트에서 다루는 건 크게 2가지입니다.


- 속성 이름과 인덱스로 데이터 가져오기

- C# LINQ 쿼리 제어


C# JSON[C# JSON] LINQ JSON 쿼리 제어 3가지 방법


속성 이름과 인덱스로 데이터 가져오기


C# JSON에서 값을 가져오는 가장 간단한 방법은 C# LINQ에서 JObject, JArray를 사용해 Item[Object] 형태로 데이터를 가져오는 것입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
string json = @"{
  'channel': {
    'title': 'James Newton-King',
    'link': 'http://james.newtonking.com',
    'description': 'James Newton-King\'s blog.',
    'item': [
      {
        'title': 'Json.NET 1.3 + New license + Now on CodePlex',
        'description': 'Annoucing the release of Json.NET 1.3',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'categories': [
          'Json.NET',
          'CodePlex'
        ]
      },
      {
        'title': 'LINQ to JSON beta',
        'description': 'Annoucing LINQ to JSON',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'categories': [
          'Json.NET',
          'LINQ'
        ]
      }
    ]
  }
}";
 
JObject rss = JObject.Parse(json);
 
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
 
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
 
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
 
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex
cs

C# LINQ 쿼리 제어


C# LINQ를 통해 JObject, JArray에 쿼리를 날릴 수 있습니다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var postTitles =
    from p in rss["channel"]["item"]
    select (string)p["title"];
 
foreach (var item in postTitles)
{
    Console.WriteLine(item);
}
 
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex
 
var categories =
    from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>()
    group c by c
    into g
    orderby g.Count() descending
    select new { Category = g.Key, Count = g.Count() };
 
foreach (var c in categories)
{
    Console.WriteLine(c.Category + " - Count: " + c.Count);
}
 
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1
cs


C# Linq[C# JSON] LINQ JSON 쿼리 제어 3가지 방법


LINQ 객체를 사용해 Deserialize


1
2
3
4
5
6
7
8
9
10
11
12
13
public class Shortie
{
    public string Original { get; set; }
    public string Shortened { get; set; }
    public string Short { get; set; }
    public ShortieException Error { get; set; }
}
 
public class ShortieException
{
    public int Code { get; set; }
    public string ErrorMessage { get; set; }
}
cs


위와 같이 수동으로 제어할 수 있다면, C# Json 객체를 보다 쉽게 제어할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
string jsonText = @"{
  'short': {
    'original': 'http://www.foo.com/',
    'short': 'krehqk',
    'error': {
      'code': 0,
      'msg': 'No action taken'
    }
  }
}";
 
JObject json = JObject.Parse(jsonText);
 
Shortie shortie = new Shortie
{
    Original = (string)json["short"]["original"],
    Short = (string)json["short"]["short"],
    Error = new ShortieException
    {
        Code = (int)json["short"]["error"]["code"],
        ErrorMessage = (string)json["short"]["error"]["msg"]
    }
};
 
Console.WriteLine(shortie.Original);
// http://www.foo.com/
 
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
cs


[C# JSON] LINQ JSON 쿼리 제어 3가지 방법

댓글