JSON.Net Convert an internal object to a C # model

I have the following JSON returning from a remote API (I cannot change the returned JSON)

{ "APITicket": { "location": "SOMEVALUE", "ticket": "SOMEVALUE" } } 

Now, using JSON.Net to convert to this model, I need 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 it works well - my problem arises when I have about 50 calls to make an API, and really don't need to create a second β€œContainer” for each. Is there a way to bind the example above directly to TicketModel?

+6
source share
3 answers

You can do it as follows:

  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 value to a TicketModel instance: var ticket = jProperty.Value.ToObject<TicketModel>(); 
+1
source

Change the JSON to look like this:

 { "location": "SOMEVALUE", "ticket": "SOMEVALUE" } 

and do

 List<TicketModel> tickets = JsonConvert.DeserializeObject<List<TicketModel>>(this.JSONResponse); 

or even

 Dictionary<string, string> tickets = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.JSONResponse); 

therefore you do not need any models.

+1
source

use Newtonsoft JArray to configure ur json before deserializing

 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; } 
+1
source

Source: https://habr.com/ru/post/949096/


All Articles