【发布时间】:2014-08-28 00:58:37
【问题描述】:
我有以下从 API 调用返回的 JSON:
{
"Success": true,
"Message": null,
"Nodes": [
{
"Title": "Title 1",
"Link": "http://www.google.com",
"Description": null,
"PubDate": "2014-06-19T13:32:00-07:00"
},
{
"Title": "Title 2",
"Link": "http://www.bing.com",
"Description": null,
"PubDate": "2014-06-26T13:14:00-07:00"
},
]
}
我有以下对象将 JSON 转换为自定义对象
[JsonObject(MemberSerialization.OptIn)]
public class MyApiResponse
{
[JsonProperty(PropertyName = "Success")]
public bool Success { get; set; }
[JsonProperty(PropertyName = "Message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "Nodes")]
public IEnumerable<object> Nodes { get; set; }
}
我能够执行以下代码行以反序列化为MyApiResponse 对象。
MyApiResponse response = JsonConvert.DeserializeObject<MyApiResponse>(json);
我想循环通过MyApiResponse对象的Nodes属性可以将它们序列化成另一个对象。当我尝试以下 sn-p 代码时,它会引发错误:
foreach(var item in response.Nodes)
{
MyObject obj = JsonConvert.DeserializeObject<MyObject>(item.ToString());
}
我需要做什么才能在foreach 循环中将item 转换为我的MyObject?
【问题讨论】:
-
所以你的问题是它为什么会抛出错误?如果是,请提供错误信息。或者您的问题是:在 foreach 循环中将 item 转换为 MyObject 需要做什么?如果是这样,由于您在 MyApiResponse 类中将其声明为节点,如果您想更改为其他内容,请确保您需要转换它
-
@ah_hau - 当我尝试循环通过
Nodes属性将它们转换为MyObject数据类型时,API 似乎抛出了 HTTP 500 错误 -
你能发布更多代码吗? HTTP 500 Internal Server Error 是一般的服务器错误,如果您已经收到您的响应,为什么它仍然调用 Web 函数?您的 JsonConvert 是否调用了在线托管的第 3 方转换器?
标签: c# json json.net json-deserialization