简体   繁体   English

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

[英]How make array insert array json in web service C#

How can I create a JsonArray with a child data object array? 如何创建带有子数据对象数组的JsonArray? I am using Web service and C#. 我正在使用Web服务和C#。

I want the result of the JsonArray to look like the following: 我希望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"
}]

First, create the models that can output the given data. 首先,创建可以输出给定数据的模型。 You need a MovieModel , a movie can have multiple image sizes and urls stored, we use a dictionary for this. 您需要一个MovieModel ,一部电影可以存储多个图像大小和URL,为此我们使用了字典。

UPDATED 更新

MovieModel.cs MovieModel.cs

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

Now you need to install Newtonsoft.Json from Nuget packages. 现在,您需要从Nuget软件包中安装Newtonsoft.Json Then import it. 然后导入。

using Newtonsoft.Json;

Initialize the model and convert to Json using SerializeObject() method. 初始化模型,并使用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);

In a real application, you would create Movie instances by getting data from a database, not initializing it for yourself as used in this example. 在实际的应用程序中,您将通过从数据库获取数据来创建Movie实例,而不是像本示例中那样自行初始化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM