0

I got this two classes

public class RootObj
{
    public int a { get; set; }
    public SubObj sub { get; set; }
}
public class SubObj
{
    public int b { get; set; }
}

The JSON string to be deserialized is like

{
    "a": 1,
    "sub": "{\"b\":2}"
}

Is there an option to deserialize such JSON simply like JsonSerializer.Deserialize<RootObj>(json)?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Jiruffe
  • 47
  • 5

1 Answers1

0

Just found a solution from a similar question

public class RootObj
{
    public int a { get; set; }
    [JsonConverter(typeof(StringToSubObjConverter))]
    public SubObj sub { get; set; }
}
public class SubObj
{
    public int b { get; set; }
}

public class StringToSubObjConverter : JsonConverter<SubObj>
{
    public override SubObj Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (var jsonDoc = JsonDocument.ParseValue(ref reader))
        {
            var jsonStr = jsonDoc.RootElement.GetRawText();
            if (jsonStr.SurroundedWith('"'))
            {
                jsonStr = jsonStr.Trim('"');
            }
            jsonStr = jsonStr.Unescape();
            return JsonSerializer.Deserialize<SubObj>(jsonStr);
        }
    }

    public override void Write(Utf8JsonWriter writer, SubObj value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}
Jiruffe
  • 47
  • 5