C# 如何使用JSON.NET反序列化并保留父对象
我有一些类似于:C# 如何使用JSON.NET反序列化并保留父对象,c#,json.net,C#,Json.net,我有一些类似于: { "companyName": "Software Inc.", "employees": [ { "employeeName": "Sally" }, { "employeeName": "Jimmy" } ] } 我想将其反序列化为: public class Company { public string companyName { get; set; } public IList<Em
{
"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; }
}
上市公司
{
公共字符串companyName{get;set;}
公共IList雇员{get;set;}
}
公营雇员
{
公共字符串employeeName{get;set;}
上市公司雇主{get;set;}
}
如何让JSON.NET设置“雇主”引用?我尝试使用
CustomCreationConverter
,但是公共重写对象ReadJson(JsonReader-reader,Type-objectType,objectexistingvalue,JsonSerializer-serializer)
方法不包含对当前父对象的任何引用。如果作为反序列化的一部分尝试这样做,这只会让您头疼。在反序列化之后执行该任务会容易得多。做一些类似于:
var company = //deserialized value
foreach (var employee in company.employees)
{
employee.employer = company;
}
或一行,如果您喜欢以下语法:
company.employees.ForEach(e => e.employer = company);
Json.net通过PreserveReferencesHandling解决了这个问题。只需设置PreserveReferencesHandling=PreserveReferencesHandling.Objects,Newtonsoft就可以为您完成这一切 问候,,
Fabianus我通过在父类中定义“”处理了类似的情况,如下所示:
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// Add logic here to pass the `this` object to any child objects
}
这适用于JSON.Net,无需任何其他设置。我实际上并不需要StreamingContext
对象
在我的例子中,子对象有一个SetParent()
方法,在这里以及以其他方式创建新的子对象时调用该方法
[OnDeserialized]
来自系统运行时序列化
,因此您无需添加JSON库引用。我知道我可以手动设置引用,但我有一个深度复杂的图形,在创建对象时更容易分配引用。你是说这会让人头疼,因为使用JSON.NET很难完成,还是因为你认为这是一个坏主意?@mprudhom我只是认为完成后序列化是一项相当简单的任务,但使用JSON.NET很难完成。省去你自己的烦恼:)实际上,在反序列化中设置它是非常简单的。也许2013年的情况并非如此。