【问题标题】:Json not returning the correct values in the desired patternJson 没有以所需的模式返回正确的值
【发布时间】:2016-02-05 20:31:41
【问题描述】:

我需要这个作为我的 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"]
}

【问题讨论】:

    标签: c# asp.net json web-services


    【解决方案1】:

    您需要使用 data 属性创建一个新类:

    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);
    }
    

    【讨论】:

    • Name property data 一切正常,符合要求
    • 我正在研究rest Ws,它给我的数据为null:
    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2014-11-26
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多