Convert JSON String To C# Object

前端 未结 14 1951
感情败类
感情败类 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:39

    add this ddl to reference to your project: System.Web.Extensions.dll

    use this namespace: using System.Web.Script.Serialization;

    public class IdName
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    
       string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
       var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
    
       string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
       var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
    
    0 讨论(0)
  • 2020-11-22 14:40

    You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.

    Class for the type of object you receive:

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
    
    }
    

    Code:

    static void Main(string[] args)
    {
    
          string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
    
          User user = JsonConvert.DeserializeObject<User>(json);
    
          Console.ReadKey();
    }
    

    this is a very simple way to parse your json.

    0 讨论(0)
  • 2020-11-22 14:43

    Another fast and easy way to semi-automate these steps is to:

    1. take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down.
    2. Update the name in the top left to your class name, it defaults to "Welcome".
    3. In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.
    4. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can now use code like:

      WebClient client = new WebClient();

      string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");

      var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);

    0 讨论(0)
  • 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<string, object>)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<MyObj>("{ \"test\":\"some data\" }");
            Console.WriteLine(routes_list.test);
    
            Console.WriteLine("Done...");
            Console.ReadKey(true);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 14:45

    Copy your Json and paste at textbox on json2csharp and click on Generate button.

    A cs class will be generated use that cs file as below

    var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
    

    Where RootObject is the name of the generated cs file;

    0 讨论(0)
  • 2020-11-22 14:47

    Or, you can use the Newtownsoft.Json library as follows:

    using Newtonsoft.Json;
    ...
    var result = JsonConvert.DeserializeObject<T>(json);
    

    Where T is your object type that matches your JSON string.

    0 讨论(0)
提交回复
热议问题