gpt4 book ai didi

android - 为什么 ASP MVC 创建 Android 不喜欢的 JSON 格式?

转载 作者:搜寻专家 更新时间:2023-11-01 09:08:23 24 4
gpt4 key购买 nike

我有一个非常基本的 ASP MVC 应用程序,它公开了一个静态的发布列表(请参见下面的代码和结果)。

代码:

    public JsonResult Index()
{
List<Publication> list = new List<Publication>() {
new Publication() { Id = 1, Name = "War and Peace" },
new Publication() { Id = 2, Name = "Harry Potter" },
new Publication() { Id = 3, Name = "Cat in the Hat" }
};
return this.Json(list, JsonRequestBehavior.AllowGet);
}

结果:

[{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]

当我尝试在 Android 中使用它时,出现以下错误:

04-15 12:00:57.331: W/System.err(209): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of [{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]

我可以删除开头的 [ 和结尾的 ],这样错误就不会出现了。另一种选择是将 { publications: 逻辑放在 android 代码的开头,但这似乎应该已经存在了。

如何更新 MVC 应用程序中的代码以生成“可供使用”版本的 JSON?

非常感谢任何帮助。

最佳答案

首先,您不应该在收到时修改您的 json 字符串,因为它可能会扰乱解析。

其次,你的Json字符串是数组格式的,因为它以[开始,以]结束。因此,您不应使用 JSONObject,而应使用 JSONArray

关于android - 为什么 ASP MVC 创建 Android 不喜欢的 JSON 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com