c# - Json 没有以所需的模式返回正确的值

标签 c# asp.net json web-services

我需要这个作为我的 json 返回。这些数据是从数据库中提取的,但目前我使用的是静态数据。

 {
        "data": [
            {
                "id": 1,
                "latitude":17.3700,
                "longitude": 78.4800,
                "gallery":
                    [
                        "assets/img/items/1.jpg"
                    ]
            }
        ]
    }

我已经在我的代码后面尝试过这个,但我没有得到想要的结果。

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public List<> getData()
    {
        Account account = new Account
        {
            id = 1,
            latitude = "17.3700",
            longitude ="78.4800",
            gallery = new List<string>
                  {
                    "assets/img/items/1.jpg",
                     "assets/img/items/2.jpg",
                  }
        };
        return new JavaScriptSerializer().Serialize(account);
    }

    public class Account
    {
        public int id { get; set; }
        public string latitude { get; set; }
        public string longitude { get; set; }
        public IList<string> gallery  { get; set; }
    }

结果:

{
 "id":2,
 "latitude":"17.3700",
 "longitude":"78.4800",
 "gallery":["assets/img/items/1.jpg","assets/img/items/2.jpg"]
}

最佳答案

您需要创建一个具有数据属性的新类:

public class Result { public object[] Data { get; set; } }

并返回:

public string getData()
{
    Result result = new Result
    {
        Data = new [] { new Account { id = 1, ... } }
    };

    return new JavaScriptSerializer().Serialize(result);
}

关于c# - Json 没有以所需的模式返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537234/

相关文章:

c# - 将具有另一个结构数组的结构从 C# 传递到 C (P/Invoke)

c# - Visual Studio 中语法着色的粒度

c# - Crystal Report ASP.NET MVC 中不显示本地镜像

c# - 如何使用 ASP.NET 跟踪下载?

C++ HTTP Web 服务器库

c# - 返回类的所有属性,而不是 null c#

C# 动态对象创建/修改?

c# - 在运行时删除静态添加的控件

json - 如何在没有 key 的情况下解析 JSON 文件?

java - Mongodb:如何使用 mongodb java 驱动程序更改嵌套文档的值