2015-11-05 100 views
4

我需要這個作爲我的JSON返回。這些數據正在從數據庫中提取,但目前我正在使用靜態數據。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"] 
} 

回答

1

你需要創建一個數據屬性的新類:

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

Name屬性'data'一切都很好,符合要求 – Jehof

+0

我正在處理其他Ws,並且它爲數據提供了空值: –