是否有一个简单的方法来填充我的c#对象与JSON对象通过AJAX传递?
这是使用JSON.stringify从页面传递给c# WEBMETHOD的JSON对象
{
"user": {
"name": "asdf",
"teamname": "b",
"email": "c",
"players": ["1", "2"]
}
}
接收JSON对象的c# webmethod
[WebMethod]
public static void SaveTeam(Object user)
{
}
c#类,表示传递给WebMethod的JSON对象的对象结构
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
在c#中使用JSON的一个好方法是使用JSON。网
快速入门和来自JSON的API文档。官方网站帮助你使用它。
下面是如何使用它的例子:
public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}