【发布时间】:2020-08-19 15:25:54
【问题描述】:
我有以下 json 响应(出于此问题的目的,我将其缩短为仅两条记录):
[{"Container_Type":"0000CART","Standard_Tare_Weight":1.0,"Container_Type_Key":21363,"Description":"CARTON BOX","Container_Type_Description":"0000CART-CARTON BOX","Default":false,"Standard_Quantity":0.0,"Master_Unit_Type_Key":null,"Master_Unit_Type":"","Standard_Pack_Display":false,"Production_Quantity_Default":false},{"Container_Type":"0000PCTN","Standard_Tare_Weight":35.0,"Container_Type_Key":21375,"Description":"RETURNABLE CONTAINER","Container_Type_Description":"0000PCTN-RETURNABLE CONTAINER","Default":false,"Standard_Quantity":0.0,"Master_Unit_Type_Key":null,"Master_Unit_Type":"","Standard_Pack_Display":false,"Production_Quantity_Default":false}]
在c#代码中存储在dynamic json中。
我想将“Container_Type”、“Standard_Tare_Weight”等键填充到单独的列表中,所以我创建了:
PropertyInfo[] dynamicProperties;
dynamicProperties = json.GetType().GetProperties();
如何在foreach下面写出返回这些属性?
foreach (var property in dynamicProperties)
{
property.Name
}
不返回“Container_Type”、“Standard_Tare_Weight”等,而是:
Type Item Item IsReadOnly HasValues First Last Count Parent Root Next Previous Path
当我通过这个 json 循环并输入属性名称“Container_Type”时:
foreach (var item in json)
{
item.Container_Type
}
它显示正确的值“0000CART”和“0000PCTN”。所以我知道这些属性存在于该 json 对象中,但是我如何从该 json 对象中动态获取它们?
假设我已经完成了这项工作,我该如何修改上面的 foreach 循环,以便从我的属性列表中获取这些属性名称?
也许我的推理是错误的,在 c# 中使用 json 对象有更好的方法。我只是想要一些灵活的方法来处理任何 json 响应并即时转换它,而无需创建模型/类,而需要在获取响应之前知道属性名称。
你能指出正确的方向吗?
【问题讨论】:
-
你能添加你的反序列化代码吗?
-
@GuruStron 我的反序列化基于 Newtosoft:
json = JsonConvert.DeserializeObject(some string from API call);where 'some string from API call' = above json from the post[{"Container_Type":"0000CART","Standard_Tare_Weight":1.0}]...