개발관련/other
json.net을 사용하여 null 인 경우 클래스의 속성을 무시하는 방법
Rateye
2021. 8. 27. 16:28
728x90
반응형
질문 : json.net을 사용하여 null 인 경우 클래스의 속성을 무시하는 방법
클래스를 JSON으로 직렬화하기 위해 Json.NET 을 사용하고 있습니다.
다음과 같은 수업이 있습니다.
class Test1
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("url")]
public string URL { get; set; }
[JsonProperty("item")]
public List<Test2> Test2List { get; set; }
}
Test2List
가 null
경우에만 Test2List
JsonIgnore()
특성을 추가하고 싶습니다. null이 아닌 경우 json에 포함하고 싶습니다.
답변
James Newton King에 따르면 : JavaScriptConvert를 사용하는 대신 직렬 변환기를 직접 만드는 경우 무시하도록 설정할 수 NullValueHandling
속성이 있습니다.
다음은 샘플입니다.
JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};
또는 @amit이 제안한대로
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
출처 : https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net
728x90
반응형