2016-11-22 31 views
0

如何創建一個JsonArray與子數據對象數組?我正在使用Web服務和C#。如何使數組插入數組JSON在Web服務C#

我想JsonArray的結果如下所示:

[{ 
    "name": "Deadpool", 
    "url": { 
     "small": "http://api.android.info/images/small/deadpool.jpg", 
     "medium": "http://api.android.info/images/medium/deadpool.jpg", 
     "large": "http://api.android.info/images/large/deadpool.jpg" 
    }, 
    "time": "February 12, 2016" 
}, 
{ 
    "name": "The Jungle Book", 
    "url": { 
     "small": "http://api.android.info/images/small/book.jpg", 
     "medium": "http://api.android.info/images/medium/book.jpg", 
     "large": "http://api.android.info/images/large/book.jpg" 
    }, 
    "time": "April 15, 2016" 
}, 
{ 
    "name": "X-Men: Apocalypse", 
    "url": { 
     "small": "http://api.android.info/images/small/xmen.jpg", 
     "medium": "http://api.android.info/images/medium/xmen.jpg", 
     "large": "http://api.android.info/images/large/xmen.jpg" 
    }, 
    "time": "May 27, 2016" 
}] 
+0

你究竟想要做什麼?你目前的問題不太清楚。你能否在你的問題中增加更多細節? –

+0

您如何訪問您的數據?從數據庫?你用linq嗎? – Yanga

+0

我想你想要的是如何創建你的類結構來將你的數據轉換成像你的例子一樣的jsonarray。這是你期望 – Seminda

回答

1

首先,創建一個可以輸出給定的數據模型。你需要一個MovieModel,一部電影可以有多個圖像大小和URL存儲,我們用這個字典。

修訂

MovieModel.cs

public class MovieModel 
{ 
    public string Name { get; set; } 
    public Dictionary<string,string> Url { get; set; } 
    public string Time { get; set; } 
} 

現在你需要從的NuGet包安裝Newtonsoft.Json。然後導入它。

using Newtonsoft.Json; 

初始化模型並使用SerializeObject()方法轉換爲Json。

var movieList = new List<MovieModel> 
{ 
    new MovieModel 
    { 
     MovieName = "Deadpool", 
     Time = DateTime.UtcNow.ToString("t"), 
     Url = new Dictionary<string, string> 
     { 
      { "small", "http://api.android.info/images/small/deadpool.jpg" }, 
      { "medium", "http://api.android.info/images/medium/deadpool.jpg" } 
     } 
    } 
    // .. add more movies .. // 
}; 

// convert to camelcase and set indentation 
var output = JsonConvert.SerializeObject(
    movieList, 
    Formatting.Indented, 
    new JsonSerializerSettings 
    { 
     ContractResolver = new CamelCasePropertyNamesContractResolver() 
    } 
); 

// testing output on console 
Console.WriteLine(output); 

在實際應用中,你將通過從數據庫中獲取數據,而不是在這個例子中使用初始化它爲自己創造電影的實例。

+0

它的作品mr.abdul,但在結果「網址」:[{「小」:「http .....」,「中」:「http。 ....「}] 我不想把」[「列表數據」url「 –

+0

爲什麼你想要刪除它? Json中的方括號表示它是一個項目數組,如果將其刪除,則消耗應用程序可能會遇到反序列化返回對象的麻煩。 – abdul

+0

,因爲在教程JSON是,所以我想創建像, 你可以檢查這個網址:api.androidhive.info/json/glide.json .. –