본문 바로가기

C# Winform

C# Winform | Json - Read, Write

by C기억저장소 2020. 8. 24.

C# Winform | Json - Read, Write

 

  Nuget 설치

 

1. Microsoft.Windows.SDK.Contracts 설치

 

2. 마이그레이션

 

3. 마이그레이션 확인

 

설정완료후 Using 추가

1
using Windows.Data.Json;
cs

 

  읽기

 

1. test JSON string

 

[{"key":1,"market":"ETH","day":1.31,"week":-2.75,"mon1":34.09,"mon6":30.17,"year1":89.76,"view":true},
{"key":2,"market":"USDT","day":-0.99,"week":-0.88,"mon1":-20.91,"mon6":-19.09,"year1":-14.39,"view":true},
{"key":3,"market":"XRP","day":0,"week":-1.4,"mon1":16,"mon6":-13.93,"year1":-5.92,"view":true},
{"key":4,"market":"XLM","day":4.14,"week":5.35,"mon1":-11.61,"mon6":24.28,"year1":37.07,"view":true},
{"key":5,"market":"LTC","day":0.32,"week":9.2,"mon1":13.6,"mon6":-28.04,"year1":-26.62,"view":true},
{"key":6,"market":"EOS","day":1.47,"week":8.75,"mon1":3.61,"mon6":-29.96,"year1":-16.37,"view":true},
{"key":7,"market":"XTZ","day":5.13,"week":-7.37,"mon1":1.1,"mon6":-12.07,"year1":193.6,"view":true},
{"key":8,"market":"BCH","day":-0.26,"week":-1.03,"mon1":1.27,"mon6":-37.01,"year1":-17.43,"view":true},
{"key":9,"market":"ETC","day":1.59,"week":-0.05,"mon1":-10.92,"mon6":-35.98,"year1":-3.21,"view":true},
{"key":10,"market":"TRX","day":2.67,"week":21.58,"mon1":23.53,"mon6":9.48,"year1":39.16,"view":true}]
cs

 

2. Code

 

private void btnRead_Click(object sender, EventArgs e)
{
    JsonArray jArray = JsonArray.Parse(jsonstring);
    for(int i=0; i< jArray.Count; i++)
    {
        JsonObject jObject = jArray[i].GetObject();
        long key = Convert.ToInt64(jObject["key"].GetNumber());
        string market = jObject["market"].GetString();
        double day = jObject["day"].GetNumber();
        double week = jObject["week"].GetNumber();
        double mon1 = jObject["mon1"].GetNumber();
        double mon6 = jObject["mon6"].GetNumber();
        double year1 = jObject["year1"].GetNumber();
        bool view = jObject["view"].GetBoolean();
 
        Console.WriteLine(key + " - " + market + " : " + day + "," + week + "," + mon1 + "," + mon6 + "," + year1 + " - " + view);
    }
}
cs

 

3. RESULT

 

  쓰기

 

1. Code

 

private void btnWrite_Click(object sender, EventArgs e)
{
    JsonArray JArray = new JsonArray();
    for (int i = 0; i < 10; i++)
    {
        JsonObject jObject = new JsonObject();
        jObject.Add("key", JsonValue.CreateNumberValue(i));
        jObject.Add("name", JsonValue.CreateStringValue("name"+i));
        bool check = true;
        if(i % 2 == 0)
        {
            check = false;
        }
        jObject.Add("bool", JsonValue.CreateBooleanValue(check));
 
        JArray.Add(jObject);
    }
    Console.WriteLine(JArray.ToString());
}
cs

 

2. RESULT