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
copy the json
{ "errorMessage": "This is an error", "returnValue": { "value": "this is what returns" } }
Check and compare with your classes