C#에서 .json file로 저장하는 방법

 

json object처리를 위해 Newtonsoft.json.dll 을 nuget 패키지 관리자에서 추가해줍니다.

 

아래와 같이 샘플로 JObject 객체를 하나 생성해주고, 속성을 지정해줍니다.

File.WriteAllText("경로","json문자열") 함수를 실행해주면 지정한 경로에 파일이 생성됩니다.

using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace JsonFileWriteTest
{
    class Program
    {
        static void Main(string[] args)
        {
            
            JObject sonSpec = new JObject(
                new JProperty("score", 9),
                new JProperty("name", "손흥민"),
                new JProperty("number", 7)
            );

            File.WriteAllText(@"D:\path2.json", sonSpec.ToString());

        }
    }
}

 

결과값 확인

 

 

지난 포스팅에서 활용했던 고속도로 구간별 통과시간 정보를 호출해 파일로 저장해보겠습니다.

https://vmpo.tistory.com/71

 

[C#] rest api 호출하기 (WebClient, WebRequest sample)

C#에서 rest api 호출하는 방법을 확인해보겠습니다. WebClient 클래스와, WebRequest 클래스를 활용해 보겠습니다. 샘플 API는 고속도로 공공데이터 포털의 API를 활용하겠습니다. 인증키 없이도 호출할 수 있어..

vmpo.tistory.com

 

아래는 고속도로 구간별 통과시간 정보를 호출해 파일로 저장하는 코드입니다.

복사해서 바로 실행 가능한 코드입니다.

 

JObject로 파싱 후 toString()으로 저장만 해주면 됩니다.

using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;

namespace JsonFileWriteTest
{
    class Program
    {
        static void Main(string[] args)
        {

            JObject sonSpec = new JObject(
                new JProperty("score", 9),
                new JProperty("name", "손흥민"),
                new JProperty("number", 7)
            );

            File.WriteAllText(@"D:\path2.json", sonSpec.ToString());


            //1.WebClient 클래스 활용
            string webClientResult = callWebRequest();
            var r = JObject.Parse(webClientResult);

            File.WriteAllText(@"D:\road.json", r.ToString());

        }


        public static string callWebRequest()
        {
            string responseFromServer = string.Empty;

            try
            {

                WebRequest request = WebRequest.Create("http://data.ex.co.kr/openapi/safeDriving/forecast?key=test&type=json");
                request.Method = "GET";
                request.ContentType = "application/json";
                request.Headers["user-agent"] = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
                using (WebResponse response = request.GetResponse())
                using (Stream dataStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    responseFromServer = reader.ReadToEnd();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return responseFromServer;
        }
    }
}

 

결과값

 

LIST
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기