Home > database >  How to deserialize a nested json string?
How to deserialize a nested json string?

Time:04-27

Suppose I have this classes:

internal class Test
{
    public string value { get; set; }

    public Test(string value)
    {
        this.value = value;
    }
}

public class Response<T>
{
    private string errorMessage { get; }
    private T returnValue { get;  }

    public Response(string errorMessage, T returnValue)
    {
        this.errorMessage = errorMessage;
        this.returnValue = returnValue;
    }

    public bool HasError() { return errorMessage != ""; }

    public bool AssertEqualsReturnValue(object obj) { return returnValue.Equals(obj); }
        
}

and I have this Main function:

string json = 
@"{
    ""errorMessage"": ""This is an error"",
    ""returnValue"": {
        ""value"": ""this is what returns""
    }
}
";

Response<Test> r = JsonSerializer.Deserialize<Response<Test>>(json); ;
Console.WriteLine(r.AssertEqualsReturnValue("this is what returns"));
Console.WriteLine(r.HasError());

I get the next error message:

System.InvalidOperationException: 'Each parameter in the deserialization constructor on type 'IntroSE.Kanban.Backend.Response`1[ConsoleApp1.Test]' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.'

It won't desirialize because I need to somehow tell the JsonSerializer I have a Test object in returnValue key. I saw some solutions online but the problem is they all use JsonConverter which is no in use anymore in .Net 6.0.

CodePudding user response:

You have defined your errorMessage and returnValue properties with private visibility. If you change them to public after that the exception will not be thrown.

Please be aware that the JsonInclude attribute can be used only in case of non-public property accessors, like private set; or private get;.

CodePudding user response:

FYI you can do this in VS

  1. copy the json

    { "errorMessage": "This is an error", "returnValue": { "value": "this is what returns" } }

  2. Choose EDIT < Paste Special > Paste JSON As Classes enter image description here

  3. Check and compare with your classes

enter image description here

  • Related