How to map JSON to C# Objects

后端 未结 4 671
忘掉有多难
忘掉有多难 2020-12-01 03:13

I am having issues with understanding how to make this happen.

Basically we have an API, the user sends a JSON of the format: (excuse the code if not perfect but yo

相关标签:
4条回答
  • 2020-12-01 03:31

    You can use Json.NET to deserialize your json string as (with some modifications to your classes)

    var yourObject =  JsonConvert.DeserializeObject<Root>(jsonstring);
    
    
    public class Root
    {
        public Profile[] Profile;
    }
    
    public class Profile
    {
        public string Name { get; set; }
        public string Last { get; set; }
        public Client Client { get; set; }
        public DateTime Date { get; set; }
    }
    
    public class Client
    {
        public int ClientId;
        public string Product;
        public string Message;
    }
    
    0 讨论(0)
  • 2020-12-01 03:32

    Easiest way I know is to use JSON.Net by newtonsoft. To make it easier to understand, I always make matching classes in C# with the same name. Then its easier to deserialize it. As an example, if it is an array of objects in js, it will map to a list of object with the same names in C#. As for the date time, its a bit tricky. Id do the client side validation and Datetime.tryParse in the serverside, itll take care of the dashes or slashes.

    var serializer = new JavaScriptSerializer();
    List<abc> abcList = serializer.Deserialize<List<abc>>(PassedInJsonString);
    
    0 讨论(0)
  • 2020-12-01 03:37

    DataContractJsonSerializer does the job, but it uses more sophisticated format for DateTime serialization.

    0 讨论(0)
  • 2020-12-01 03:39

    You can use a JSON library for this, for example Newtonsoft.Json which is free. It will map json to your types automatically.

    Sample:

        public static T Deserialize<T>(string json)
        {
            Newtonsoft.Json.JsonSerializer s = new JsonSerializer();
            return s.Deserialize<T>(new JsonTextReader(new StringReader(json)));
        }
    

    There is also a NuGet package available.

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