'newtonsoft'에 해당되는 글 1건

  1. 2022.01.26 C# JSON - JSON 데이터 파싱하고 원하는대로 보여주기 3
반응형

C#으로 JSON 데이터를 파싱하고 원하는 값을 찾아보자.

 

아래와 같은 JSON 데이터 파일을 준비한다.

 

data.json
0.00MB

 

Newtonsoft.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.IO;
 
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonData = File.ReadAllText(@"d:\data.json");
            //Console.WriteLine(jsonData);
 
            JObject jObject = JObject.Parse(jsonData);
            //Console.WriteLine(jObject.ToString());
 
            Console.WriteLine("Last Update: " + (jObject["LastUpdate"]));
            Console.WriteLine("SalesRecord Count: " + (jObject["SalesRecord"]).Count());
            Console.WriteLine("SalesRecord[2]\"total\": " + jObject["SalesRecord"][2]["total"]);
 
            JToken jToken = jObject["SalesRecord"];
            foreach (JToken data in jToken)
            {
                Console.WriteLine("■ " + data["date"+ ": " + data["item"]);
            }
 
            Item item = JsonConvert.DeserializeObject<Item>(jsonData);
            Console.WriteLine("Last Update: " + item.LastUpdate);
            foreach (Record record in item.SalesRecord)
            {
                Console.WriteLine("■ " + record.date + ": " + record.item);
            }
 
            string serializedJsonData = JsonConvert.SerializeObject(item);
            //Console.WriteLine(serializedJsonData);
            JObject serializedJObject = JObject.Parse(jsonData);
            //Console.WriteLine(serializedJObject);
        }
 
        // 모든 필드명이 json 데이터의 key와 일치해야 한다.
        class Item
        {
            public string LastUpdate;
            public List<Record> SalesRecord;
        }
 
        class Record
        {
            public string date;
            public string item;
            public int price;
            public int quantity;
            public int total;
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

JSON 데이터가 원하는대로 출력된다.

 

반응형
Posted by J-sean
: