将JObject转换为自定义实体 - c#

时间:2014-08-28 00:58:38

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

我有一个从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); 

我想循环遍历Nodes对象的MyApiResponse属性,可以将它们序列化为另一个对象。当我尝试以下代码片段时,它会抛出一个错误:

foreach(var item in response.Nodes)
{
     MyObject obj = JsonConvert.DeserializeObject<MyObject>(item.ToString());
}

item循环中将MyObject转换为foreach,我需要做什么?

1 个答案:

答案 0 :(得分:1)

您只需要定义一个类来表示一个Node,然后将Nodes类中的MyApiResponse属性更改为List<Node>(或IEnumerable<Node>如果您愿意而不是IEnumerable<object>。当您调用JsonConvert.DeserializeObject<MyApiResponse>(json)时,一次性反序列化整个JSON响应。不应该单独对每个子项进行反序列化。

[JsonObject(MemberSerialization.OptIn)]
public class Node
{
    [JsonProperty(PropertyName = "Title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "Link")]
    public string Link { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "PubDate")]
    public DateTime PubDate { get; set; }
}

[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 List<Node> Nodes { get; set; }
}

然后:

MyApiResponse response = JsonConvert.DeserializeObject<MyApiResponse>(json);

foreach (Node node in response.Nodes)
{
    Console.WriteLine(node.Title);
}