- 以字符串格式序列化数据
string data = "{"VerifyOTPResult":{"ReturnCode":"200","ReturnMsg":"Invalid OTP.","Data":{"BrokerName":null,"ErrorMsg":null,"Id":null,"IsValidUser":false,"RoleName":null}}}";
- 对象类
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; }
}
- 使用newtonsoft.json组装用于DeserializeObject尝试1:
var decRes = JsonConvert.DeserializeObject<VerifyOTPResult>(content);
输出除了int属性
以外,在每个属性中获取null尝试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
}
}
}
我无法避免。如何将其转换为我的对象类?
您的JSON包括VerifyOTPResult
,但实际上是具有VerifyOTPResult
属性的A 不同的对象。您应该对某些包装类别(即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; }
}
yo可能会尝试serializer.Deserialize<MyObj>(str);
以e.g var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);