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)?

0

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.