gpt4 book ai didi

c# - 使用 C# 进行数据映射的动态 json 字段模式

转载 作者:行者123 更新时间:2023-11-30 20:37:22 24 4
gpt4 key购买 nike

我从 Web API 获取这种类型的 JSON 数据:

Data: {
FromDate: "2016-03-01",
Comment: "Bla bla",
...
},
FieldInfo: {
Items: [
{
Id: "FromDate",
Required: true,
DataType: "date"
},
{
Id: "Comment",
Required: true,
DataType: "string"
},
...
]
}

我需要将它序列化为 C# 对象并将其转换为不同的表示形式,它应该看起来像这样:

  {
FieldInfo: {
Items: [
{
Id: "FromDate",
Required: true,
DataType: "date",
Value: "2016-03-01"
},
{
Id: "Comment",
Required: true,
DataType: "string"
Value: "Bla bla"
},
...
]
}

基本上将字段值映射到其模式,因此不会被分离。当然,最简单的方法就是为每个字段写很多 if,如果我们考虑到字段架构和字段是动态的以便它们可以更改,这将不是非常优雅的解决方案,甚至是不可行的。我可以依赖的属性是 FieldInfo Item 模式中的 Id,它应该是 Data 对象中的属性名称。解决方案之一可能是使用反射,以便将 Id 值映射到 C# 对象表示中的属性名称。我的问题是这个问题可能有另一种解决方案,或者有一些工具可以帮助我实现这个目标?

最佳答案

使用 JSON.NET ,您可以将 JSON 解析为 JObject并像这样操纵它:

// Parse your json string into a JObject
JObject o = JObject.Parse(json);

// Retrieve the "Data" part of the json, i.e,
// the object that contains the values
var data = o["Data"];

// Retrieve the "FieldInfo" part. We will add values to this part.
var fieldInfo = o["FieldInfo"];

foreach (var token in fieldInfo["Items"])
{
var item = (JObject) token;

// Add the Value property to each item, get the value from the
// corresponding field
item["Value"] = data[(string)item["Id"]];
}

变量 fieldInfo 将包含您想要的信息。当然,创建一个新的 JObject 来包含信息会更简洁。但该示例显示了如何检索和映射所需的值。

关于c# - 使用 C# 进行数据映射的动态 json 字段模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com