我从远程API返回以下
JSON(我无法修改返回的
JSON)
{ "APITicket": { "location": "SOMEVALUE","ticket": "SOMEVALUE" } }
现在使用JSON.Net将其转换为模型我必须创建2个模型.
public class TicketModel { public string location { get; set; } public string ticket { get; set; } } public class TicketContainer { public TicketModel APITicket { get; set; } }
并做一些像..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
这很有效 – 当我有大约50次调用API并且真的不想为每个调用创建第二个“容器”时,我的问题就出现了.有没有办法将上面的例子直接绑定到TicketModel?
你可以这样做:
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>();