【发布时间】: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