Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.Net Convert inner object to C# Model

Tags:

c#

json.net

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?

like image 708
LiamB Avatar asked Jul 10 '13 08:07

LiamB


2 Answers

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>();
like image 180
Reda Avatar answered Oct 07 '22 00:10

Reda


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;
    }
like image 40
Ashok Damani Avatar answered Oct 06 '22 23:10

Ashok Damani