我在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; }
}
然后我们添加一些数据:
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;
最后两行将使用Newtonsoft Json将记录类型对象序列化为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"}]}]}
现在我需要使用javascript和POST将json创建到WEB API端点。我不知道的是如何在javascript中创建对象。
我知道有序列化对象的JSON.stringify(对象),但是如何创建List ???
我知道我可以这样做:
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);
答案 0 :(得分:3)
您应该将JavaScript Array
用于.NET集合。
var record = {
name: "Whatever",
description: "Something else",
artists: [{
name: "Artist Name",
album: "Some Album",
songs: [{
name: "Some Song"
}]
}]
};
Web API会将JSON视为不区分大小写。
答案 1 :(得分:-1)
您需要将此代码用于jQuery REST POST JSON列表
var jsonObj = [];
$.each({ name: "John", lang: "JS" }, function (key,value) {
jsonObj.push(
{
key: value
});
});