将 JSON 对象图中的对象位置指定为 JsonConvert

在像这样收到的 JSON 中:


{ name { first_name: 'Foo', last_name: 'Bar' }, emails: [ {value: 'foo@bar.com' } ]

有没有办法告诉 JsonConvert 到,例如:


value把数组第一个元素的属性取emails到下面的POCO属性Email中?


从JSON中的对象中读取first_name属性放到下面POCO的属性中?nameFirstName


我试过做这种路径,但那是行不通的。这有语法吗?


public class DaPOCO

{

  [JsonProperty("name.first_name")]

  public FirstName { get; set; }


  [JsonProperty("emails[0].value")]

  public Email { get; set;} 

}

我知道,如果缺少语法,我可以自己从动态对象中读取属性,如下所示:


dynamic data = JsonConvert.DeseralizeObject(json);

DaPOCO poco = new DaPOCO

{

  FirstName = data.name.first_name;

  Email = data.emails?.ElementAt(0)?.value;

};

我只是想知道是否已经有内置的基于属性的语法来执行此操作。


慕田峪4524236
浏览 108回答 1
1回答

慕田峪9158850

根据您发布的序列化 json,下面应该是要反序列化到的正确模型。我相信您了解当前模型与您拥有的 json 不兼容public class Name{&nbsp; &nbsp; public string first_name { get; set; }&nbsp; &nbsp; public string last_name { get; set; }}public class Email{&nbsp; &nbsp; public string value { get; set; }}public class DaPOCO{&nbsp; &nbsp; public Name name { get; set; }&nbsp; &nbsp; public List<Email> emails { get; set; }}你可以试试下面的东西using System;using System.Linq;using Newtonsoft.Json.Linq;public class Program{&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string responseString = @"{ name: { first_name: 'Foo', last_name: 'Bar' }, emails: [ {value: 'foo@bar.com' } ] }";&nbsp; &nbsp; &nbsp; &nbsp; JObject jo = JObject.Parse(responseString);&nbsp; &nbsp; &nbsp; &nbsp; JObject obj = (jo["emails"] as JArray).FirstOrDefault(x => !string.IsNullOrEmpty(x.Value<string>("value"))) as JObject;&nbsp; &nbsp; &nbsp; &nbsp; DaPOCO poco = new DaPOCO&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FirstName = ((jo["name"] as JObject)["first_name"]).ToString(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Email = obj["value"].ToString(),&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(poco.FirstName + "\t" + poco.Email);&nbsp; &nbsp; }}public class DaPOCO{&nbsp; public string FirstName { get; set; }&nbsp; public string Email { get; set;}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP