Deserializing JSON array into strongly typed .NET object

前端 未结 8 708
一个人的身影
一个人的身影 2020-11-30 07:35

When I can call the 3rd party api and get back a single class worth of data everything deserialises fine using this code

TheUser me = jsonSerializer.Deseria         


        
相关标签:
8条回答
  • 2020-11-30 07:58

    This solution seems to work for me and gets around having to code a bunch of classes with "Data" in them.

    public interface IDataResponse<T> where T : class
    {
        List<T> Data { get; set; }
    }
    
    public class DataResponse<T> : IDataResponse<T> where T : class
    {
       [JsonProperty("data")]
       public List<T> Data { get; set; }
    }
    

    I should have included this to begin with, here is an example method using the above:

    public List<TheUser> GetUser()
    {
        var results = GetUserJson();
        var userList = JsonConvert.DeserializeObject<DataResponse<TheUser>>(results.ToString());
    
        return userList.Data.ToList();
    } 
    
    0 讨论(0)
  • 2020-11-30 08:05

    try

    List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);
    
    0 讨论(0)
提交回复
热议问题