I have the following JSON coming back from a remote API (I cannot modify the JSON returned)
{
    "APITicket": {
        "location": "SOMEVALUE",
        "ticket": "SOMEVALUE"
    }
}
Now using JSON.Net to convert to this to a model I have to create 2 models.
  public class TicketModel
    {
        public string location { get; set; }
        public string ticket { get; set; }
    }
    public class TicketContainer
    {
        public TicketModel APITicket { get; set; } 
    }
and do something like..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
and this works well - my problem arises when I have around 50 calls to make to the API and really dont fancy creating a second 'Container' for each. Is there a way to bind the example above directly to the TicketModel?
You can do it this way:
var json = @"
            {
                'APITicket': {
                    'location': 'SOMEVALUE',
                    'ticket': 'SOMEVALUE'
                }
            }";
//Parse the JSON:
var jObject = JObject.Parse(json);
//Select the nested property (we expect only one):
var jProperty = (JProperty)jObject.Children().Single();
//Deserialize it's value to a TicketModel instance:
var ticket = jProperty.Value.ToObject<TicketModel>();
                        use Newtonsoft's JArray to customize ur json before deserialize  
public List<APITicket> JsonParser(string json)   
    {
        Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(json);
        var list = new List<APITicket>();
        foreach(var item in jArray)
        {
            list.Add(
                new APITicket { location = item["APITicket"]["location"],
                                ticket =   item["APITicket"]["ticket"]            
                }
            );
        }
        return list;
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With