Ian Vink
Ian Vink

Reputation: 68830

ServiceStack: Deserializing a Collection of JSON objects

I have a simple json string which contains a collection of objects http://sandapps.com/InAppAds/ads.json.txt

When I call GetAsync to get the objects, the collection returns 1 element instead of 4 and it's empty:

new JsonServiceClient ().GetAsync<List<CrossSell>> (url, Success, Failure);

My class is simple:

class CrossSell 
{
    public string ID { get; set; }  
    public string AppCategory { get; set; } 
    public string AppID { get; set; }   
    public string Name { get; set; }    
    public string ImageUrl { get; set; }    
    public string Copy { get; set; }    
    public string Device { get; set; }  
    public string Link { get; set; }    
}

Upvotes: 2

Views: 1137

Answers (2)

mythz
mythz

Reputation: 143399

The JSON assumes a response DTO like:

class CrossSellResponse {
  List<CrossSell> CrossSells { get; set; }
}

new JsonServiceClient().GetAsync<CrossSellResponse> (url, Success, Failure);

and not a bare array as your C# example suggests:

new JsonServiceClient ().GetAsync<List<CrossSell>> (url, Success, Failure);

Upvotes: 3

Ian Vink
Ian Vink

Reputation: 68830

I found the answer. You need to create an overall wrapper class that holds the JSON response. I call mine CrossSellResponse

public class CrossSellResponse
{
   public List< CrossSell> CrossSells {get; set;}
}

The class CrossSell defines the data in the collection and matches the field names in a case sensitive way. The name of the response payload property CrossSells matches the name of the collection in the json stream.

Upvotes: 0

Related Questions