我在使用newtonSoft JSON反序列化JSON时返回了null值。 这是我的JSON:
{"odata.metadata":"https://graph.abc.com/testapi",
"value":
[{"capabilityStatus":"Enabled",
"consumedUnits":2,
"objectId":"c9992e5ef110_6fd2c87-1e91e994b900",
"prepaidUnits":{"enabled":25,"suspended":0,"warning":0},
"servicePlans":
[{"servicePlanId":"4ccb","servicePlanName":"YAMMER_ENTERPRISE"},
{"servicePlanId":"bea4","servicePlanName":"RMS_S_ENTERPRISE"},
{"servicePlanId":"43de","servicePlanName":"OFFICESUBSCRIPTION"},
{"servicePlanId":"0fea","servicePlanName":"MCOSTANDARD"},
{"servicePlanId":"e95be","servicePlanName":"SHAREPOINTWAC"},
{"servicePlanId":"5dbe","servicePlanName":"SHAREPOINTENTERPRISE"},
{"servicePlanId":"efb8","servicePlanName":"EXCHANGE_S_ENTERPRISE"}],
"skuId":"42f0-b197",
"skuPartNumber":"ENTERPRISEPACK"}]}
这是我的课程:
public class PrepaidUnits
{
public int enabled { get; set; }
public int suspended { get; set; }
public int warning { get; set; }
}
public class ServicePlan
{
public string servicePlanId { get; set; }
public string servicePlanName { get; set; }
}
public class Value
{
public string capabilityStatus { get; set; }
public int consumedUnits { get; set; }
public string objectId { get; set; }
public PrepaidUnits prepaidUnits { get; set; }
public List<ServicePlan> servicePlans { get; set; }
public string skuId { get; set; }
public string skuPartNumber { get; set; }
}
public class Graphdata
{
public string odata_metadata { get; set; }
public List<Value> value { get; set; }
}
所以这就是问题,当我使用以下语句反序列化时,我得到servicePlanId和servicePlanName的返回值。我在这做错了什么?
var graphAPIDataDeserialized = JsonConvert.DeserializeObject<ServicePlan>(graphResult);
但是,当我使用Graphdata类时,我可以看到JSON响应中的所有值:
var graphAPIDataDeserialized = JsonConvert.DeserializeObject<Graphdata>(graphResult);
提前感谢您的帮助!
答案 0 :(得分:2)
这是任何JSON解析器的预期行为。你给它的字符串应该代表你想要离开它的对象,所以当你说:
JsonConvert.DeserializeObject<ServicePlan>(graphResult)
...您正在指示它将图形结果反序列化为ServicePlan
对象。它会创建一个ServicePlan
,查看您给它的对象(“图形结果”),找不到名为servicePlanId
的属性等,因此它不会在这些属性上设置任何值
如果您尝试创建ServicePlan
,则需要传递一个更像{"servicePlanId":"4ccb","servicePlanName":"YAMMER_ENTERPRISE"}
的字符串值。
另一方面,如果您试图从反序列化的图表结果中获取ServicePlans,您可以说:
JsonConvert.DeserializeObject<Graphdata>(text).value[0].servicePlans