0

I have little problem with deserialization. In variable test I get null. Other thing how return correct json in method.

*In picture I cast to object but normally I cast to ClaimValue :)

Have you got any idea what I made wrong?

       foreach (var claim in claims)
        {
            claimValues.Add(new ClaimValue { Type = claim.Type, Value = claim.Value, ValueType = claim.ValueType });
        }

        string json = JsonConvert.SerializeObject(new
        {
            results = claimValues
        });

        var test = JsonConvert.DeserializeObject<ClaimValue>(json);

        return json;
    }
}

public class ClaimValue
{
    public string Value { get; set; }
    public string ValueType { get; set; }
    public string Type { get; set; }
}

enter image description here

Rafał Developer
  • 2,135
  • 9
  • 40
  • 72

1 Answers1

2

You're wrapping the claims list in an anonymous object, so your JSON will look like this:

{
    "results" : [
        { 
            "Type" : "foo",
            "ValueType" : "bar",
            "Value" : "baz"
        },
        {
            // ...
        }
    ]
}

You cannot deserialize that as one ClaimsValue, because that doesn't match that structure.

Generate classes to contain the wrapper and the list, something like this:

public class ClaimsContainer
{
    public List<ClaimsValue> results { get; set; }
}

Then deserialize into that:

var test = JsonConvert.DeserializeObject<ClaimsContainer>(json);

See also Deserializing JSON into an object.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272