如何反序列化对象值中带有花括号的字符串?

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

我有这个字符串需要反序列化。

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

这是我的代码,我正在使用 XUnit 进行测试。

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]);

这是我的 VerificationResponseError class.

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

但是,它在

处中断

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

听起来你的 class 不正确,不应该是这样的吗?

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; }
}

您可以使用此工具验证 https://json2csharp.com/

您的 class 不代表您的 json 结构。接下来试试:

public class VerificationResponseError
{
    public Errors errors { get; set; }
    public string title { get; set; }
    public int status { get; set; }
}

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

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