[英]Convert Dynamic Json to Something more Concrete
How can I deserialize the JSON below to a C# array or something more manageable. 如何将以下JSON反序列化为C#数组或更易于管理。
{
"data": [
{
"PropertyName": [
{
"Key1": "test",
"Key2": "afafa"
},
{
"Key1": "test",
"Key2": "afafa"
}
],
"PropertyName2": [
{
"Key1": "test",
"Key2": "afafa"
},
{
"Key1": "test",
"Key2": "afafa"
}
]
}
]
}
It comes in as a dynamic parameter like this: 它以动态参数形式出现,如下所示:
public IActionResult SAve([FromBody] dynamic mapping)
I normally would make this a concrete class but "PropertyName" will change to different names, so I need something flexible. 我通常将其设为一个具体的类,但“ PropertyName”将更改为不同的名称,因此我需要一些灵活的东西。 The contents of it can be concrete as it is just two properties.
它的内容可以是具体的,因为它只是两个属性。
I am thinking that it could be like a dictionary. 我认为这可能像字典。
Dictionary<string, ConcreteClass>()
I just don't know how to get it into that form. 我只是不知道如何将其转换为这种形式。
Edit. 编辑。
I have gone ahead and did the suggestion but it does not work 我已经进行了建议,但是没有用
{{
"data": [
{
"propertyName": [
{
"key1": 1,
"key2": "1"
},
{
"key1": 2,
"key2": "2"
}
]
}
]
}}
I tried to convert like this 我试图这样转换
var ddd = JsonConvert.DeserializeObject<List<MappingDto>>(mapping.data.ToString());
this makes an empty object in the array. 这将在数组中创建一个空对象。 If I don't have it wrapped in a collection then I get a different error
如果我没有将其包装在集合中,则会收到其他错误
public class MappingDto
{
public List<Dictionary<string, List<Item>>> Items { get; set; }
}
public class Items
{
public string Key1{ get; set; }
public string Key2{ get; set; }
}
For this JSON, a concrete class structure that handles the dynamic property names as you described would look like this: 对于此JSON,处理您所描述的动态属性名称的具体类结构如下所示:
public class MappingDto
{
public List<Dictionary<string, List<Item>>> Data { get; set; }
}
public class Item
{
public string Key1 { get; set; }
public string Key2 { get; set; }
}
Be sure to update your method signature to use the new class instead of dynamic
: 确保更新方法签名以使用新类而不是
dynamic
:
public IActionResult SAve([FromBody] MappingDto mapping)
You can then access the data like this (for example): 然后,您可以像下面这样访问数据:
foreach (var dict in mapping.Data)
{
foreach (var kvp in dict)
{
Debug.WriteLine(kvp.Key);
foreach (var item in kvp.Value)
{
Debug.WriteLine(" Key1: " + item.Key1);
Debug.WriteLine(" Key2: " + item.Key2);
}
}
}
Fiddle: https://dotnetfiddle.net/OGylPh 小提琴: https : //dotnetfiddle.net/OGylPh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.