Home > Mobile >  Deserialize RESTSharp Response Ignoring Headers
Deserialize RESTSharp Response Ignoring Headers

Time:07-30

I am looking to deserialize the data returned from a REST API. I am struggling to get the data to map to my object. It seems like I am probably looking at the entire JSON response and not isolating in on the 'data' portion of the response. My response contains attributes for page, pagesize, hasmore and totalcount which I wish to ignore in my mapping. I want to map the array of data with only the fields that correspond to my object (there will be some additional fields in the response I do not need).

JSON Object

Here is the code that fails:

var businessUnits = JsonConvert.DeserializeObject<List<BusinessUnit>>(response.Content);

I'm really not sure what I am doing wrong. I've tried a dozen or so variations with absolutely no success. I can see the data I need in the data array; but any attempts to map it have failed.

CodePudding user response:

you have to parse a json at first, after this you can select what part of the content you want to deserialize

var businessUnits = JObject.Parse(response.Content)["data"]
                           .ToObject<List<BusinessUnit>>();

CodePudding user response:

Your JSON is not an IEnumerable. Without some sample data this might not be exact but close:

var BusinessUnits = JsonConvert.DeserializeAnonymousType(response.Content, new
{
    JSON = new {
        data = new List<BusinessUnit>() 
    }
}).JSON.data;

It would be nice if you could share the response.Content and BusinessUnit class.

EDIT: Here is a sample:

void Main()
{
    var BusinessUnits = JsonConvert.DeserializeAnonymousType(responseContent, new
    {
        JSON = new
        {
            data = new List<BusinessUnit>()
        }
    }).JSON.data;
    
    foreach (var bu in BusinessUnits)
    {
        Console.WriteLine($"P1: {bu.P1}, P2: {bu.P2}");
    }
}

public class BusinessUnit
{ 
    public int P1 { get; set; }
    public string P2 { get; set; }
}

static readonly string responseContent = @"
{
  ""JSON"": {
     ""page"":1,
     ""pageSize"":50,
     ""hasMore"":false,
     ""totalCount"":"""",
     ""data"": [
        {
           ""P1"":1234,
           ""P2"": ""Hello1"",
           ""P3"": ""HelloX"",
        },
        {
           ""P1"":12345,
           ""P2"": ""Hello2"",
           ""P3"": ""HelloY"",
        },
     ]
  }
}
";

This outputs:

P1: 1234, P2: Hello1
P1: 12345, P2: Hello2
  • Related