를 사용하여 System.Text.Json.JsonSerializer
모델을 부분적으로 역 직렬화 하려고 하므로 속성 중 하나는 원본 JSON이 포함 된 문자열로 읽 힙니다.
public class SomeModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Info { get; set; }
}
예제 코드
var json = @"{
""Id"": 1,
""Name"": ""Some Name"",
""Info"": {
""Additional"": ""Fields"",
""Are"": ""Inside""
}
}";
var model = JsonSerializer.Deserialize<SomeModel>(json);
Info
원본 JSON의 Info 개체를 문자열로 포함 하는 속성 인 모델을 생성해야 합니다.
{
"Additional": "Fields",
"Are": "Inside"
}
기본적으로 작동하지 않고 예외가 발생합니다.
System.Text.Json.JsonException : ---> System.InvalidOperationException : 'StartObject'토큰 유형의 값을 문자열로 가져올 수 없습니다.
지금까지 시도한 것 :
public class InfoToStringConverter : JsonConverter<string>
{
public override string Read(
ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
return reader.GetString();
}
public override void Write(
Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
모델에 다음과 같이 적용하십시오.
[JsonConverter(typeof(InfoToStringConverter))]
public string Info { get; set; }
옵션을 추가하십시오. JsonSerializer
var options = new JsonSerializerOptions();
options.Converters.Add(new InfoToStringConverter());
var model = JsonSerializer.Deserialize<SomeModel>(json, options);
그래도 동일한 예외가 발생합니다.
System.Text.Json.JsonException : ---> System.InvalidOperationException : 'StartObject'토큰 유형의 값을 문자열로 가져올 수 없습니다.
필요한 것을 요리하기위한 올바른 조리법은 무엇입니까? 를 사용하여 비슷한 방식으로 작동했습니다 Newtonsoft.Json
.
최신 정보
저에게는 중첩 된 JSON 객체를 가능한 한 원본으로 유지하는 것이 중요합니다. 따라서 Dictionary
바람직하지 않은 변경 사항을 도입하는 것이 두렵기 때문에 역 직렬화 및 직렬화와 같은 옵션을 피하고 싶습니다 .
.NET Framework에서 중첩 된 JSON 개체를 올바르게 읽는 방법을 찾았습니다 JsonConverter
. 완전한 솔루션은 다음과 같습니다.
public class SomeModel
{
public int Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(InfoToStringConverter))]
public string Info { get; set; }
}
public class InfoToStringConverter : JsonConverter<string>
{
public override string Read(
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (var jsonDoc = JsonDocument.ParseValue(ref reader))
{
return jsonDoc.RootElement.GetRawText();
}
}
public override void Write(
Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
코드 자체에는 옵션을 만들 필요조차 없습니다.
var json = @"{
""Id"": 1,
""Name"": ""Some Name"",
""Info"": {
""Additional"": ""Fields"",
""Are"": ""Inside""
}
}";
var model = JsonSerializer.Deserialize<SomeModel>(json);
Info
속성 의 원시 JSON 텍스트 에는 가독성을 높이기 위해 예제에서 소개 한 추가 공백도 포함됩니다.
그리고 그의 대답에 @PavelAnikhouski가 언급 한 것처럼 모델 표현과 직렬화가 혼합되어 있지 않습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다