【问题标题】:How to iterate JSON in C# and add every object to List?如何在 C# 中迭代​​ JSON 并将每个对象添加到 List?
【发布时间】:2020-11-17 23:05:51
【问题描述】:

我有一个这种格式的 JSON:

{
  "id1": {
    "id": "183",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-27"
  },
  "id2": {
    "id": "182",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-23"
  },
  "id3": {
    "id": "180",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-20"
  },
  "id4": {
    "id": "179",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-19"
  }
}

我需要遍历它并将每个项目添加到新的 ArrayList:

ArrayList NewList = new ArrayList();

我需要它,以便稍后循环遍历我的 ArrayList 并检索我想要的任何对象。 我尝试使用这个网站https://json2csharp.com/,但它返回这个:

public class Id1    {
    public string id { get; set; } 
    public string contentname { get; set; } 
    public string content { get; set; } 
    public string created { get; set; } 
}

public class Id2    {
    public string id { get; set; }  
    public string contentname { get; set; } 
    public string content { get; set; } 
    public string created { get; set; } 
}

public class Root    {
    public Id1 id1 { get; set; } 
    public Id2 id2 { get; set; } 
}

这对我来说不是很有用,因为会有 100 多个不同的 id 并且每天都会添加更多。

有什么方法可以做我想做的事吗?它适用于我的 Xamarin 项目,在 Android 中我使用了 Volley 库,它运行良好,但我在 C# 中一直在苦苦挣扎。

感谢您的帮助:)

编辑: 这是生成我的 json 的 PHP:

<?php
class SeznamNovinekApi extends BaseApi
{
    public function ToProcess($parametry)
    {
        $novinkyInfo = Database::SqlGetFetchAll("select id, pageid, contentname, content, created from mainpagesarticles where pageid = ? order by created desc", array('novinky'));

        $i = 0;
        foreach ($novinkyInfo as $info)
        {
            $i++;
            $obj = ["id" => $info["id"], "pageid" => $info["pageid"], "contentname" => $info["contentname"], "content" => $info["content"], "created" => $info["created"]];
            $this->json['id' . $i] = $obj;
        }
    }
}
?>

【问题讨论】:

  • 您可以控制 JSON 吗?因为您的 JSON 不是对象数组。
  • 是的,我愿意,但它是用 PHP 编写的,所以我不太确定如何:/ 你认为我必须更改我的整个 json 以使其与 C#“兼容”吗?
  • 你最好修复你的 JSON。你能发布生成这个的 PHP 代码吗?
  • 您正在构建一个关联数组,而实际上并不需要它。相反,只需构建一个简单的数据数组,然后返回该数组的 json

标签: c# json xamarin


【解决方案1】:

理想情况下,您的 JSON 应该看起来更像这样:

{[
  {
    "id": "183",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-27"
  },
  {
    "id": "182",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-23"
  },
  {
    "id": "180",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-20"
  },
  {
    "id": "179",
    "contentname": "Title",
    "content": "Some text",
    "created": "2020-07-19"
  }
]}

只是 JSON 对象的普通数组。您不需要外部标识符,但您确实需要一个数组。您之前的 JSON 是具有许多子对象的单个对象。

有了这个,(和伪代码)任何 JSON 转换器基本上都会像这样工作:

MyType[] arrayOfObjects = JSON.Convert<MyType>(myJson);

【讨论】:

    【解决方案2】:

    我完全使用了你的 json。

    创建模型:

    public class Data
    {
        public int Id { get; set; }
        public string ContentName { get; set; }
        public string Content { get; set; }
        public DateTime Created { get; set; }
    }
    

    打开命名空间:

    using Newtonsoft.Json.Linq;
    

    使用此代码:

    var text = File.ReadAllText("test.json");
    var json = JObject.Parse(text);
    var list = new List<Data>();
    
    foreach (var prop in json.Properties())
    {
        var value = prop.Value;
        var data = new Data
        {
            Id = value["id"].Value<int>(),
            ContentName = value["contentname"].ToString(),
            Content = value["content"].ToString(),
            Created = value["created"].Value<DateTime>()
        };
        list.Add(data);
    }
    

    【讨论】:

      【解决方案3】:

      通过您问题下方的 cmets,看到您有能力修复您的 Json,我建议您首先将您的 JSON 修复为类似这样的内容(它具有一个实际的 id 元素数组)。

      {
        "ids": [
          {
            "id": "183",
            "contentname": "Title",
            "content": "Some text",
            "created": "2020-07-27"
          },
          {
            "id": "182",
            "contentname": "Title",
            "content": "Some text",
            "created": "2020-07-23"
          },
          {
            "id": "180",
            "contentname": "Title",
            "content": "Some text",
            "created": "2020-07-20"
          },
          {
            "id": "179",
            "contentname": "Title",
            "content": "Some text",
            "created": "2020-07-19"
          }
        ]
      }
      

      按顺序完成后,Visual Studio 中有一个非常漂亮的工具可帮助您基于此 JSON 构建类定义。将 json 复制到剪贴板并复制到:编辑 -> 选择性粘贴 -> 将 JSON 粘贴为类。您可以在打开 *.cs 文件时执行此操作。

      这将为您构建以下 JSON。

      public class Ids
      {
          public Id[] ids { get; set; }
      }
      
      public class Id
      {
          public string id { get; set; }
          public string contentname { get; set; }
          public string content { get; set; }
          public string created { get; set; }
      }
      

      之后,过程就很简单了:

      private static void Main(string[] args)
      {
          var json = File.ReadAllText("test.json");
          var ids = JsonSerializer.Deserialize<Ids>(json);
          Console.WriteLine(ids);
      }
      

      【讨论】:

      • 假设 OP 出于某种原因想要一个对象,该对象只不过是其他对象的数组。这对我来说是一种代码味道,在父类中没有其他有用的东西,尤其是名称为“Ids”的东西不像 Int64。
      • 我相信 OP 必须有潜力根据他的用例范围找出更好的属性命名。这不是这个 anwser 的目标。
      【解决方案4】:

      非常感谢每一位回复的人,现在 mjwills 的 Quicktype 代码可以正常工作,但我可能会改正我的 json 并正确执行 :) 谢谢!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-11
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多