【问题标题】:JSON array of objects to .NET ObjectJSON 对象数组到 .NET 对象
【发布时间】:2011-01-10 12:18:51
【问题描述】:

我有一个大对象回来了,我只需要一小部分数据。我正在查看示例here。我基本上想做同样的事情,但问题是我会有一个“错误”对象数组。

所以,它看起来像这样

{
    "short": {
        "original": "http://www.foo.com/",
        "short": "krehqk",
        "error": [
            {
                "code": 0,
                "msg": "No action taken" 
            },
            {
                "code": 0,
                "msg": "No action taken" 
            }
        ] 
    }
}

有没有一种简单的方法可以使用 JObject.Parse 甚至是 Linq to JSON 来完成此任务?我最好只使用 JsonConvert.DeserializeObject 而不包括我创建的 .NET 对象中不需要的属性/对象吗?

更新 在这里使用上面的 JSON 是我的测试...

[TestMethod]
public void ParseStuffTest()
{
    JObject json = JObject.Parse(shortJson);

    Shortie shortie = new Shortie
    {
        Original = (string)json["short"]["original"],
        Short = (string)json["short"]["short"],
        Error = new ShortError
        {
            Code = (int)json["short"]["error"]["code"],
            ErrorMessage = (string)json["short"]["error"]["msg"]
        }
    };
    Assert.IsNotNull(shortie);
}

public class Shortie
{
    [JsonProperty]
    public string Original { get; set; }

    [JsonProperty]
    public string Short { get; set; }

    [JsonProperty]
    public List<ShortError> Error{ get; set; }
}

public class ShortError
{
    [JsonProperty]
    public int Code { get; set; }
    [JsonProperty]
    public string ErrorMessage { get; set; }
}

这是错误:无法将类型“Unit_Tests.Test.ShortError”隐式转换为“System.Collections.Generic.List”

我错过了什么?


这就是我想出的……我只是不喜欢它,因为我正在使用的真实对象要大得多,并且数组对象有多个属性。这是我唯一的选择??? (除了明显的 JsonConvert.Deserialize)

[TestMethod]
public void ParseStuffTest()
{
    JObject json = JObject.Parse(shortJson);
    var errors = json["short"]["error"].Children().ToList();
    var shortErrors = new List<ShortError>();
    foreach (var error in errors)
    {
        var shortError = new ShortError
                             {
                                 Code = (int)error["code"],
                                 ErrorMessage = (string)error["msg"]
                             };
        shortErrors.Add(shortError);
    }
    var shortie = new Shortie
    {
        Original = (string)json["short"]["original"],
        Short = (string)json["short"]["short"],
        Error = shortErrors
    };
    Assert.IsNotNull(shortie);
    Assert.AreEqual(2, shortie.Error.Count);
}

【问题讨论】:

    标签: .net json


    【解决方案1】:

    如果你的目标类型(也就是反序列化到的类型)有一个名为 error 的属性,它是一个 List 或数组,这仍然可以工作。在这种情况下我会避免使用 Linq,因为(在我看来)它会增加不必要的开销,而这对于序列化来说是完全不必要的。

    JavaScriptDeserializer (example) 和 Json 类都是专门为此设计的,因此请充分利用这些工具。

    如果您真的只想反序列化对象的一部分,您可以在反序列化之前对 JSON 源执行一些基本的字符串操作。在您的示例中,搜索 "error": 之间的所有内容,并且它匹配关闭 ']' 并将其从 JSON 字符串中删除。

    【讨论】:

      【解决方案2】:

      一位同事刚刚路过,向我展示了我想使用 Linq to JSON 做什么...

      [TestMethod]
      public void ParseStuffTest()
      {
          JObject json = JObject.Parse(shortJson);
          var shortie = new Shortie
          {
              Original = (string)json["short"]["original"],
              Short = (string)json["short"]["short"],
              Error = json["short"]["error"].ToList().Select(
                  c => new ShortError { Code = (int)c["code"], ErrorMessage = (string)c["msg"] }).ToList()
          };
          Assert.IsNotNull(shortie);
          Assert.AreEqual(2, shortie.Error.Count);
      }
      

      没什么。 :-)

      【讨论】:

        猜你喜欢
        • 2013-03-18
        • 1970-01-01
        • 2020-03-31
        • 2018-11-13
        • 2020-08-02
        • 1970-01-01
        • 2019-04-28
        • 2023-03-26
        • 1970-01-01
        相关资源
        最近更新 更多