北城已荒凉 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 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页