我想将所有从MySQL数据库返回的值解析为JSON文件。所以我这样写我的php:
foreach ($Posts->Show() as $Key => $Post) {
$Data ['POST'][$Post['Post_Id']]["Id"]=$Post['Post_Id'];
$Data ['POST'][$Post['Post_Id']]["Url"] = "https://eastcloud.ir/Blog?=" . $Post['Post_Url'];
$Data ['POST'][$Post['Post_Id']]["Name"] = $Post['Post_Name'];
$Data ['POST'][$Post['Post_Id']]["Date"] = $Post['Post_Date'];
$Data ['POST'][$Post['Post_Id']]["Author"] = $Post['Post_Author'];
$Data ['POST'][$Post['Post_Id']]["Image"] = "https://eastcloud.ir/" . $Post['Post_Image'];
$Data ['POST'][$Post['Post_Id']]["Tags"] = "https://eastcloud.ir/" . $Post['Post_Image'];
$ID++;
}
给定的json是这样的:
POST
17
{
Id "17"
Url "https://eastcloud.ir/Blog?=Simplist-Documentations"
Name "Simplist Documentations"
Date "23 May, 2018"
Author "Milad"
Image "https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png"
Tags "https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png"
}
循环将继续获取值并将其解析为JSON(可使用here的JSON文件),但是如果我想在Json2Sharp上使用给定的JSON,它将告诉给定了无效的JSON文件。 解决办法是什么?如何使用PHP从数据库值创建JSON?
答案 0 :(得分:0)
使用json_encode创建json。这不是创建它的最佳方法 手动。
要了解输出的问题,正确的数据JSON格式应如下所示:
{
"Id":"17",
"Url":"https://eastcloud.ir/Blog?=Simplist-Documentations",
"Name":"Simplist Documentations",
"Date":"23 May, 2018",
"Author":"Milad",
"Image":"https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png",
"Tags":"https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png"
}
每行而不是最后一行之后,请仔细查看引号和双点和逗号。
答案 1 :(得分:0)
您尝试使用json_encode()
方法吗?
foreach ($Posts->Show() as $Key => $Post) {
$Data['POST'][] = [
$Post['Post_Id'] = [
"Id" => $Post['Post_Id'],
"Url" => "https://eastcloud.ir/Blog?=" . $Post['Post_Url'],
"Name" => $Post['Post_Name'],
"Date" => $Post['Post_Date'],
"Author" => $Post['Post_Author'],
"Image" => "https://eastcloud.ir/" . $Post['Post_Image'],
"Tags" => "https://eastcloud.ir/" . $Post['Post_Image'],
],
];
$ID++;
}
// here is your json from db fetching loop
$json = json_encode($Data);
更新1.0
请检查我根据您生成的JSON
{
"POST" : [
{
"Id": "17",
"Url": "https://eastcloud.ir/Blog?=Simplist-Documentations",
"Name": "Simplist Documentations",
"Date": "23 May, 2018",
"Author": "Milad",
"Image": "https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png",
"Tags": "https://eastcloud.ir/Content/Shared/Posts/SimplistV2.png"
},
{
"Id": "18",
"Url": "https://eastcloud.ir/Blog?=angular-2-vs-react",
"Name": "انگیولار ۲ در مقابل ریاکت",
"Date": "23 May, 2018",
"Author": "Milad",
"Image": "https://eastcloud.ir/Content/Shared/Posts/432644.png",
"Tags": "https://eastcloud.ir/Content/Shared/Posts/432644.png"
}
]
}
来自json2csharp的响应
public class POST
{
public string Id { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public string Date { get; set; }
public string Author { get; set; }
public string Image { get; set; }
public string Tags { get; set; }
}
public class RootObject
{
public List<POST> POST { get; set; }
}
答案 2 :(得分:-1)
您可以使用数据库中的json_encode()数据