小编典典

如何将JSON对象转换为自定义C#对象?

c#

有没有一种简单的方法可以使用通过AJAX传递的JSON对象填充C#对象?

这是使用JSON.stringify从页面传递给C#WEBMETHOD的JSON对象

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

接收JSON对象的C#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; }
}

阅读 353

收藏
2020-05-19

共1个答案

小编典典

在C#中使用JSON的一种好方法是使用JSON.NET

快速入门和API文档JSON.NET
-官方网站
帮助你使用它。

如何使用它的示例:

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);
 }
2020-05-19