Convert JSON String To C# Object

前端 未结 14 1937
感情败类
感情败类 2020-11-22 14:27

Trying to convert a JSON string into an object in C#. Using a really simple test case:

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
obj         


        
14条回答
  •  孤街浪徒
    2020-11-22 14:44

    You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

    If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:

    var json_serializer = new JavaScriptSerializer();
    var routes_list = (IDictionary)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
    Console.WriteLine(routes_list["test"]);
    

    If you want to use the dynamic keyword, you can read how here.

    If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

    class MyProgram {
        struct MyObj {
            public string test { get; set; }
        }
    
        static void Main(string[] args) {
            var json_serializer = new JavaScriptSerializer();
            MyObj routes_list = json_serializer.Deserialize("{ \"test\":\"some data\" }");
            Console.WriteLine(routes_list.test);
    
            Console.WriteLine("Done...");
            Console.ReadKey(true);
        }
    }
    

提交回复
热议问题