字符串对象无法反序列化为特定的对象C#

时间:2019-02-21 15:29:43

标签: c# .net json json.net deserialization

  1. 以字符串格式序列化数据
string data = "{\"VerifyOTPResult\":{\"ReturnCode\":\"200\",\"ReturnMsg\":\"Invalid OTP.\",\"Data\":{\"BrokerName\":null,\"ErrorMsg\":null,\"Id\":null,\"IsValidUser\":false,\"RoleName\":null}}}";
  1. 对象类
public class VerifyOTPResult {
  public string ReturnCode { get; set; }
  public string ReturnMsg { get; set; }
  public ValidateUserResult Data { get; set; }
}

public class ValidateUserResult {
  public string Id { get; set; }
  public bool IsValidUser { get; set; }
  public string BrokerName { get; set; }        
  public string RoleName { get; set; }
  public string ErrorMsg { get; set; }
}
  1. 将Newtonsoft.Json程序集用于DeserializeObject 尝试1:
var decRes = JsonConvert.DeserializeObject<VerifyOTPResult>(content);

输出 除int属性外,每个属性都为空

尝试2:

var decRes1 = JsonConvert.DeserializeObject(content);

输出

{
    "VerifyOTPResult": {
        "ReturnCode": "200",
        "ReturnMsg": "Invalid OTP.",
        "Status": null,
        "CurrentPage": 0,
        "Data": {
            "BrokerName": null,
            "ErrorMsg": null,
            "Id": null,
            "IsValidUser": false,
            "RoleName": null
        }
    }
}

我无法DeserializeObject。如何将其转换为我的对象类?

2 个答案:

答案 0 :(得分:1)

您的JSON包含VerifyOTPResult,但实际上是具有VerifyOTPResult属性的不同对象。您应该反序列化某些包装类(即VerifyOTPResultResponse

void Main()
{
    string data = "{\"VerifyOTPResult\":{\"ReturnCode\":\"200\",\"ReturnMsg\":\"Invalid OTP.\",\"Data\":{\"BrokerName\":null,\"ErrorMsg\":null,\"Id\":null,\"IsValidUser\":false,\"RoleName\":null}}}";

    var decRes = JsonConvert.DeserializeObject<VerifyOTPResultResponse>(data);

    Console.WriteLine(decRes.VerifyOTPResult.ReturnCode);
    Console.WriteLine(decRes.VerifyOTPResult.ReturnMsg);

    // Output:
    // 200
    // Invalid OTP.
}

public class VerifyOTPResultResponse
{
    public VerifyOTPResult VerifyOTPResult { get; set; }
}

public class VerifyOTPResult
{
    public string ReturnCode { get; set; }
    public string ReturnMsg { get; set; }
    public ValidateUserResult Data { get; set; }
}

public class ValidateUserResult
{
    public string Id { get; set; }
    public bool IsValidUser { get; set; }
    public string BrokerName { get; set; }
    public string RoleName { get; set; }
    public string ErrorMsg { get; set; }
}

答案 1 :(得分:0)

您也可以尝试serializer.Deserialize<MyObj>(str);例如var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);