Dayat San Dayat San - 15 days ago 7
JSON Question

How make array insert array json in web service C#

How can I create a JsonArray with a child data object array? I am using Web service and C#.

I want the result of the JsonArray to look like the following:

[{
"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"
}]

Answer

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.

UPDATED

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. Then import it.

using Newtonsoft.Json;

Initialize the model and convert to Json using SerializeObject() method.

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.