Json does not return the correct values ​​in the desired template

I need this when my json returns. This data is retrieved from the database, but I am currently using static data.

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

I tried this in my code, but I am not getting the desired result.

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

Result:

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

You need to create a new class with the data property:

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

and return that:

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

    return new JavaScriptSerializer().Serialize(result);
}
+1
source

Source: https://habr.com/ru/post/1614545/


All Articles