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

[C# Json] LINQ, JsonPath로 데이터 가져오기

by vicddory 2017. 8. 19.

[C# JSON] LINQ, JSONPath로 데이터 가져오기


C# JSON SelectToken()은 JObject에 있는 문자열, 정수 등을 가져오는데 사용합니다.

이때 C# JSONPath, LINQ도 함께 사용할 수 있어 실제 구현 방법은 총 3가지입니다.


[C# JSON] LINQ, JSONPath로 데이터 가져오기[[C# JSON] LINQ, JSONPath로 데이터 가져오기]


C# Json 1. SelectToken


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
43
44
45
1JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");
 
string name =
    (string)o.SelectToken(
        "Manufacturers[0].Name");
// Acme Co
 
decimal productPrice = 
    (decimal)o.SelectToken(
        "Manufacturers[0].Products[0].Price");
// 50
 
string productName = 
    (string)o.SelectToken(
        "Manufacturers[1].Products[0].Name");
// Elbow Grease
cs

C# Json 2. SelectToken() : JSONPath


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
43
44
45
46
47
48
49
1JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");
 
// manufacturer with the name 'Acme Co'
JToken acme = 
    o.SelectToken(
        "$.Manufacturers[?(@.Name == 'Acme Co')]");
 
Console.WriteLine(acme);
// { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }
 
// name of all products priced 50 and above
IEnumerable<JToken> pricyProducts =
    o.SelectTokens("$..Products[?(@.Price >= 50)].Name");
 
foreach (JToken item in pricyProducts)
{
    Console.WriteLine(item);
}
// Anvil
// Elbow Grease
cs


C# Json 3. SelectToken() : LINQ


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1IList<string> storeNames = 
    o.SelectToken("Stores").Select(
        s = > (string)s).ToList();
// Lambton Quay
// Willis Street
 
IList<string> firstProductNames = 
    o["Manufacturers"].Select(m = > 
        (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
 
decimal totalPrice = 
    o["Manufacturers"].Sum(m = > 
        (decimal)m.SelectToken("Products[0].Price"));
// 149.95
cs


[C# JSON] LINQ, JSONPath로 데이터 가져오기

댓글