我们能把一个动态JSON解析成一个对象List<DiffModel>列表吗?
public class DiffModel
{
public string Property { get; set; }
public string OldValue { get; set; }
public string NewValue { get; set; }
} JSON是在图书馆的帮助下生成的,它有助于比较2个JSON对象并找出它们之间的差异。这些差异被存储为一个JToken
用JToken方法生成的示例JSON值
{
"Id": [
78485,
0
],
"ContactId": [
767304,
0
],
"TextValue": [
"text value",
"text14"
],
"PostCode": [
null
]
}在JSON中,对象中第一项的值是
DiffModel [0] = Property ="id" OldValue="78485" NewValue="0"
DiffModel [1] = Property ="contactId" OldValue="767304" NewValue="0"
DiffModel [2] = Property ="TextValue" OldValue="text value" NewValue="text14"
DiffModel [3] = Property ="PostCode" OldValue= null NewValue=null我们能在动态JSON属性之间导航并构建类似的模型吗?
发布于 2021-11-10 15:02:12
您可以定义如下数据模型:
struct DiffModel
{
public string Property { get; init; }
public object OldModel { get; init; }
public object NewModel { get; init; }
}我使用过struct,但您可以使用class,record,任何您喜欢的。
然后,您可以将JToken转换为Dictionary<string, object[]>。
var rawModel = patch.ToObject<Dictionary<string, object[]>>();最后,您需要的只是DiffModel和KeyValuePair<string, object[]>之间的映射。
var diffModels = rawModel
.Select(pair => new DiffModel
{
Property = pair.Key,
OldModel = pair.Value.First(),
NewModel = pair.Value.Last(),
}).ToArray();https://stackoverflow.com/questions/69914585
复制相似问题