如何在Web服务C#中使数组插入数组json

时间:2016-11-22 04:28:13

标签: c# arrays json web-services

如何使用子数据对象数组创建JsonArray?我正在使用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"
}]

1 个答案:

答案 0 :(得分:1)

首先,创建可以输出给定数据的模型。您需要一个MovieModel,一部电影可以存储多个图片大小和网址,我们会为此使用字典。

<强>已更新

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

在实际应用程序中,您可以通过从数据库获取数据来创建Movie实例,而不是像本示例中那样自己初始化它。