我有在C#以下類:jQuery的REST POST JSON名單<Object>
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; }
}
然後,我們添加了一些數據:
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;
的最後兩行會序列記錄類型對象JSON使用Newtonsoft Json,這裏是導致的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"}]}]}
現在我需要創建這個JSON使用JavaScript和POST,json到WEB API端點。我不知道的是如何在javascript中創建對象。
我知道有JSON.stringify(對象),將序列化對象,但我怎麼能創建列表?
我知道我可以做這樣的事情:
var record =
{
Name: "Whatever",
Description: "Something else",
//How can I make the List<object>
};
我在想陣列,可能這是正確的......是這樣的:
var record =
{
Name: "Whatever",
Description: "Something else",
Artists:
{
"Name": "Artist Name",
"Album": "Some Album".
"Songs":
{
"Name": "SongName"
}
},
};
和最後一個:
JSON.stringify(record);
什麼是列出了問題? – Andrei
嗯,我需要使用JavaScript創建該JSON示例(以該格式)。結果將發佈到ASP.NET Web API端點,並將作爲Record對象類型進行轉換。我不知道如何創建相當於C#在JavaScript中的列表
我猜我必須使用arrys ...但不知道 – user2818430