【问题标题】:Convert JObject to custome entity - c#将 JObject 转换为自定义实体 - c#
【发布时间】: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


【解决方案1】:

您只需定义一个类来表示一个节点,然后将MyApiResponse 类中的Nodes 属性更改为List&lt;Node&gt;(或IEnumerable&lt;Node&gt;,如果您愿意)而不是IEnumerable&lt;object&gt;。当您调用JsonConvert.DeserializeObject&lt;MyApiResponse&gt;(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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多