Search code examples
c#jsonxunit

How to DeserializeObject a string with a curly braces in the value?


I have this string which I need to deserialize.

"{\"errors\":{\"validationError\":[\"Custom error message here.\"]},\"title\":\"One or more validation errors occurred.\",\"status\":400}"

This is my code and I am using XUnit for my testing.

var response = await client.GetAsync("api/ABC/Check?draftId=" + draftId);

var responseString = await response.Content.ReadAsStringAsync();

var result = JsonConvert.DeserializeObject<VerificationResponseError>(responseString);
Assert.Equal("Custom error message here.", result.validationError[0]);

and this is my VerificationResponseError class.

public class VerificationResponseError {
    public string errors { get; set; }
    public List<string> validationError { get; set; }
}

But, it breaks at

var result = JsonConvert.DeserializeObject<VerificationResponseError>(responseString);


Solution

  • Sounds like you have an incorrect class, shouldn't it be something like this instead?

    public class Errors
    {
        public List<string> validationError { get; set; }
    }
    
    public class VerificationResponseError
    {
        public Errors errors { get; set; }
        public string title { get; set; }
        public int status { get; set; }
    }
    

    You can use this tool to verify that https://json2csharp.com/