北城已荒凉 2010-02-11 18:30 采纳率: 0%
浏览 365
已采纳

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

Is there an easy way to populate my C# Object with the JSON object passed via AJAX?

//This is the JSON Object passed to C# WEBMETHOD from the page using JSON.stringify

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

//C# WebMetod That receives the JSON Object

[WebMethod]
public static void SaveTeam(Object user)
{

}

//C# Class that represents the object structure of JSON Object passed in to the WebMethod

public class User
{
    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

转载于:https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object

  • 写回答

13条回答 默认 最新

  • perhaps? 2010-02-11 18:33
    关注

    A good way to use JSON in C# is with JSON.NET

    Quick Starts & API Documentation from JSON.NET - Official site help you work with it.

    An example of how to use it:

    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);
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器