C#에서 Newtonsoft.Json 라이브러리를 사용해 Object를 JSON 직렬화를 할때,
null인 필드는 제외 하고 싶은 경우가 있습니다.
직렬화 함수 실행시, 아래 객체를 추가해 진행하면 null 필드를 제외해서 json으로 변환할 수 있습니다.
new JsonSerializerSettings{
NullValueHandling = NullValueHandling.Ignore
}
아래와 같이 Test1클래스를 정의하고 samplefield 값에는 값을 지정하지 않으면
null필드로 판단해 json 변환시 제외처리 됩니다.
new JsonSerializerSettings{
NullValueHandling = NullValueHandling.Ignore
} 를 넣었을 경우와 넣지 않은 경우를 각각 출력해 보도록 하겠습니다.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
namespace JsonFileWriteTest
{
class Test1
{
[JsonProperty("@id", Order = 2)]
public string ID { get; set; }
[JsonProperty("@label", Order = 1)]
public string Label { get; set; }
[JsonProperty("@url",Order = 0)]
public string URL { get; set; }
[JsonProperty("@samplefield", Order = 3)]
public string samplefield { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Test1 test = new Test1()
{
ID = "TESTID",
URL = "http://vmpo.tistory.com",
Label = "label"
};
var djsonNull = JsonConvert.SerializeObject(test);
var djsonIgnoreNull = JsonConvert.SerializeObject(
test,
new JsonSerializerSettings{
NullValueHandling = NullValueHandling.Ignore
});
var res = JObject.Parse(djsonNull);
var res2 = JObject.Parse(djsonIgnoreNull);
Console.WriteLine(res);
Console.WriteLine(res2);
}
}
}
아래와 같이 null필드가 들어간 경우와 제외된 경우의 출력 결과를 확인 할 수 있습니다.
LIST
'C#' 카테고리의 다른 글
[C#] JsonProperty attribute 순서 정렬해서 직렬화 하기 (order by) (0) | 2019.10.23 |
---|---|
[C#] rest api 호출하기 (WebClient, WebRequest sample) (12) | 2019.10.21 |
최근댓글