【发布时间】:2018-08-15 06:42:35
【问题描述】:
我使用这种方法从列表中生成 JSON:
last code
但返回 JSON 有如下错误:
期望对象或数组,而不是字符串
多个 JSON 根元素
您在this 链接中看到 JSON 文件并在this 站点中对其进行测试:
编辑:
我用这个改变我的代码:
[HttpPost]
[Route("api/Users/GetAllGoodInCat")]
public object GetAllGoodInCat([FromBody]GoodsCatId goodsCatId)
{
try
{
if (goodsCatId.id != 0)
{
var getCat = (from a in db.goodsGroups
where a.Id == goodsCatId.id
select a).SingleOrDefault();
if (getCat != null)
{
var getAllfood = from a in db.goods
where a.groupId == goodsCatId.id
orderby a.Id
select a;
var resultList = new List<string>();
foreach (var good in getAllfood)
{
var obj = new SearchGoods()
{
good = new MyGoods
{
id = good.Id,
name = good.name,
price = good.price,
brand = new MyGoodsBrand
{
id = getCat.Id,
name = getCat.title,
image = getCat.image
}
}
};
resultList.Add(new JavaScriptSerializer().Serialize(obj));
}
return resultList;
}
}
return message.ProgramError();
}
catch (Exception)
{
return message.ProgramError();
}
}
private class AllCat
{
public int id;
public string name;
public string image;
public SubLevelOne subLevelOne;
}
private class SubLevelOne
{
public int id;
public string name;
public string image;
public SubLevelTwo subLevelTwo;
}
private class SubLevelTwo
{
public int id;
public string name;
public string image;
}
现在我的 json 是这样的链接:
[
"{\"good\":{\"id\":1,\"name\":\"برنج دانه بلند محسن\",\"price\":20000,\"brand\":{\"id\":22,\"name\":\"برنج محسن\",\"image\":\"testmy.png\"}}}",
"{\"good\":{\"id\":2,\"name\":\"برنج عطری\",\"price\":30000,\"brand\":{\"id\":22,\"name\":\"برنج محسن\",\"image\":\"testmy.png\"}}}",
"{\"good\":{\"id\":3,\"name\":\"برنج سر سیاه\",\"price\":15000,\"brand\":{\"id\":22,\"name\":\"برنج محسن\",\"image\":\"testmy.png\"}}}"
]
但我想要像this这样的东西
还有(\)是json文件吗?
【问题讨论】:
-
为什么不使用 Newtonsoft JSON.NET?
-
这可能会解决您的问题
Newtonsoft.Json.JsonConvert.SerializeObject(getCat); -
您可以使用Newtonsoft。它是使用 .NET 项目管理 json 对象的第三方工具。下载Newtonsoft.Json Nuget 并参考教程。它真的很容易。
-
@MohitShrivastava 为什么要像前任一样构建 JSON。有问题吗?
-
不要自己创建 json 字符串。以某种方式构建您的对象,它们代表最终所需的 JSON 结构,然后在最顶部的元素上使用
JsonConvert.SerializeObject(),就像您已经为resultList所做的那样。顺便说一句,根据 JSON 规范,属性名称和字符串值必须用双引号"括起来,而不是像你一样用单引号'括起来。