c# - 如何将JSON对象转换为Custom C#对象?

有没有一种简单的方法来用通过Ajax传递的JSON对象填充我的C对象?
这是使用json.stringify从页面传递给c webmethod的json对象。

{
    "user": {
        "name": "asdf",
        "teamname": "b",
        "email": "c",
        "players": ["1", "2"]
    }
}

c接收JSON对象的webmetod
[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.NET
Quick Starts & API Documentation来自JSON.NET - Official site帮助您使用它。
如何使用它的示例:

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);
 }

评论