상세 컨텐츠

본문 제목

[.NET] System.Text.Json.JsonException 'The JSON value could not be converted to System.String' 에러

.NET

by 코딩하는 박줄기 2022. 10. 20. 23:00

본문

728x90
반응형

System.Text.Json문자열이 아닌 값을 문자열 속성으로 역직렬화하지 않습니다. 문자열 필드에 대해 문자열이 아닌 값을 받으면 다음 메시지와 함께 JsonException이 반환됩니다.

The JSON value could not be converted to System.String

 

필드열 형식이 맞지 않아 예외 발생

 

필드열 형식이 맞지 않아 예외 발생

역직렬화 하려는 클래스의 문자 필드열과 숫자 필드열을 구분하여 정의해야 합니다.

 

역직렬화 성공 코드

using System.Text.Json;

string jsonString = @"
{
  ""Name"": ""박진우"",
  ""Age"": 28
}";

Person Person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine(Person);

public class Person
{
    public string? Name { get; set; }
    public int Age { get; set; }
}

 

참조

728x90
반응형

관련글 더보기

댓글 영역