反序列化不一致的JSON属性(数组中的嵌套对象) [英] Deserialize inconsistent JSON property (nested object in an array)
问题描述
我正在尝试反序列化由第三方提供的,包含不一致属性的JSON文件。我正在使用Newtonsoft.Json。不幸的是,我无法控制这些文件的创建,因此我只能处理提供的文件。
I am attempting to deserialize a JSON file that has been provided from a third party which contains inconsistent properties. I am using Newtonsoft.Json. Unfortunately I have no control over the creation of these files so I am stuck with handling what is provided.
我已经对该文件中的另一个问题提供了解决方案,已记录在案/已回答。在此处反序列化不一致的JSON属性,这是我在此文件中确定的最后一个问题。我相信可以以相同的方式处理此问题,但是我正在努力解决。
I have already had a solution provided to another issue in this file which is documented / answered here Deserialize inconsistent JSON property and this is the final issue that I have identified in this file. I believe this issue can be handled in the same manner however I am struggling to work it out.
此问题如下。
文件包含以下属性:
"rolePerson": [
{
"firstName": "John",
"lastName": "Doe",
"middleNames": "Smith",
"title": "mr"
}
]
但是文件偶尔包含:
"rolePerson": [
{
"rolePerson": {
"firstName": "John",
"lastName": "Doe",
"middleNames": "Smith",
"title": "mr"
}
}
]
我需要做的是每当上述第二种情况发生时,对象内容就会像第一种情况那样反序列化。即内部对象包装器被丢弃/忽略,并且内部包装器被丢弃。
这是一个棘手的情况,但我相信将上面链接的解决方案中提供的方法结合起来可以得到某种利用。
This is a tricky situation but I believe incorporating the approach provided in the linked solution above is able to be utilized somehow.
推荐答案
感谢 dbc 的评论回复,我能够使用他们的建议来解决此问题。
Thanks to the comment response from dbc I was able to solve this issue using their advice.
作为参考,对我的RolePerson类的修改如下以解决此问题
For reference, the modification to my RolePerson class to handle this issue is as follows
public class RolePerson
{
[JsonProperty("rolePerson")]
RolePerson NestedSerialization
{
set
{
this.firstName = value?.firstName;
this.lastName = value?.lastName;
this.middleNames = value?.middleNames;
this.title = value?.title;
}
}
public string firstName { get; set; }
public string lastName { get; set; }
public string middleNames { get; set; }
public string title { get; set; }
}
可以看到他们的演示小提琴的链接此处
A link to their demo fiddle can be seen here
这篇关于反序列化不一致的JSON属性(数组中的嵌套对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!