2013-07-10 11 views
6

Ho il seguente JSON ritorno da un API remota (non riesco a modificare il JSON restituito)JSON.Net Convertire oggetto interno a C# modello

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

Ora utilizzando JSON.Net per convertire a questo ad un modello Devo creare 2 modelli.

public class TicketModel 
    { 
     public string location { get; set; } 
     public string ticket { get; set; } 
    } 

    public class TicketContainer 
    { 
     public TicketModel APITicket { get; set; } 
    } 

e fare qualcosa di simile ..

var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse); 

e questo funziona bene - il mio problema sorge quando ho circa 50 telefonate da fare alle API e davvero non voglia creare una seconda 'Container' per ogni. C'è un modo per legare l'esempio sopra direttamente al TicketModel?

+0

Se avete bisogno di deserialise tra ogni chiamata API allora c'è davvero nessun modo intorno a questo. È possibile eseguire la deserializzazione batch dopo che sono state restituite le 50 chiamate API. –

+0

Ciao @SamLeach Ho 50 chiamate API diverse, quindi non è una quantità di chiamate, ma più semplicemente un problema nella creazione di modelli Contenitore che non sono utili solo per la Deserializzazione! – LiamB

risposta

1

si può fare in questo modo:

 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>(); 
1

Modificare il JSON in modo che appaia come questo

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

e fare

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

o anche

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

quindi non hanno bisogno di alcuna modelli.

+0

Ciao Sam, non posso modificare il JSON in quanto si tratta di un'API esterna. - Aggiornamento della domanda per chiarire. – LiamB

+0

Perché no? Se viene restituito Json, puoi fare quello che vuoi con esso. –

1

uso Newtonsoft's JArray a personalizzare ur JSON prima 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; 
    } 
Problemi correlati