I'm having the following classes on C#:
public class Record { public Record() { this.Artists = new List<Artist>(); } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public List<Artist> Artists { get; set; } } public class Artist { public Artist() { this.Songs = new List<Song>(); } public int Id { get; set; } public string Name { get; set; } public string Album { get; set; } public List<Song> Songs { get; set; } } public class Song { public Song() { } public int Id { get; set; } public string Name { get; set; } } Then we add some data:
Record record = new Record(); record.Id = 1; record.Name = "Some music"; record.Description = "Something..."; Artist artist = new Artist(); artist.Id = 1; artist.Name = "Bob Marley"; artist.Album = "Legend"; Song song = new Song(); song.Id = 1; song.Name = "No woman no cry"; artist.Songs.Add(song); song = new Song(); song.Id = 2; song.Name = "Could you be loved"; artist.Songs.Add(song); record.Artists.Add(artist); artist = new Artist(); artist.Id = 2; artist.Name = "Major Lazer"; artist.Album = "Free the universe"; song = new Song(); song.Id = 2; song.Name = "Get free"; artist.Songs.Add(song); song = new Song(); song.Id = 2; song.Name = "Watch out for this"; artist.Songs.Add(song); record.Artists.Add(artist); string jsonVal = JsonConvert.SerializeObject(record); textBox1.Text = jsonVal; The last 2 lines will serialize the record type object to JSON using Newtonsoft Json and here is the resulted JSON:
{"Id":1,"Name":"Some music","Description":"Something...","Artists":[{"Id":1,"Name":"Bob Marley","Album":"Legend","Songs":[{"Id":1,"Name":"No woman no cry"},{"Id":2,"Name":"Could you be loved"}]},{"Id":2,"Name":"Major Lazer","Album":"Free the universe","Songs":[{"Id":2,"Name":"Get free"},{"Id":2,"Name":"Watch out for this"}]}]} Now I need to create this JSON using javascript and POST that json to WEB API endpoint. What I don't know is how to create the object in javascript.
I know there is JSON.stringify(object) that will serialize the object, but how can I create the List ???
I know I can do something like this:
var record = { Name: "Whatever", Description: "Something else", //How can I make the List<object> }; I'm thinking about array and probably this is the right one ... something like this:
var record = { Name: "Whatever", Description: "Something else", Artists: { "Name": "Artist Name", "Album": "Some Album". "Songs": { "Name": "SongName" } }, }; and last:
JSON.stringify(record);