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());
}
}
}
결과값 확인
지난 포스팅에서 활용했던 고속도로 구간별 통과시간 정보를 호출해 파일로 저장해보겠습니다.
[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
'C# > 기본' 카테고리의 다른 글
[C#] 문자열 찾기 및 존재 여부 확인(indexof , Contains) (1) | 2019.10.25 |
---|---|
[C#] iso 8601 format UTC datetime 만들기(yyyy-MM-ddTHH:mm:ssZ) (0) | 2019.10.24 |
[ironpython] C#에서 python 코드 실행하기 (6) | 2019.10.13 |
C# tryparse 숫자 체크 (number check) (1) | 2019.09.28 |
C# PadLeft, PadRight 특정 문자 붙이기 (0) | 2019.09.28 |
최근댓글