我有一些JSON,如:
{
"companyName": "Software Inc.",
"employees": [
{
"employeeName": "Sally"
},
{
"employeeName": "Jimmy"
}
]
}
我想把它反序列化成:
public class Company
{
public string companyName { get; set; }
public IList<Employee> employees { get; set; }
}
public class Employee
{
public string employeeName { get; set; }
public Company employer { get; set; }
}
我怎么能有JSON。NET设置"雇主"参考?我尝试使用CustomCreationConverter
,但public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
方法不包含对当前父对象的任何引用。
这只会让你感到头疼如果你想把它作为反序列化的一部分。在反序列化之后执行任务要容易得多。执行如下命令:
var company = //deserialized value
foreach (var employee in company.employees)
{
employee.employer = company;
}
或单行代码,如果您喜欢语法:
company.employees.ForEach(e => e.employer = company);
我通过定义一个"回调"来处理类似的情况。在父类中,像这样:
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// Add logic here to pass the `this` object to any child objects
}
这适用于JSON。Net,无需任何其他设置。我实际上并不需要StreamingContext
对象。
在我的情况下,子对象有一个SetParent()
方法,在这里调用,也当一个新的子对象以其他方式创建时。
[OnDeserialized]
来自System.Runtime.Serialization
,所以你不需要添加JSON库引用
Json.net用preserverreferenceshandling解决了这个问题。简单地设置PreserveReferencesHandling = PreserveReferencesHandling。对象和Newtonsoft为您做这一切。
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_PreserveReferencesHandling.htm问候,法比