【发布时间】:2020-06-10 04:36:10
【问题描述】:
当我将它传递给方法时,我试图让我的方法返回 matchKey 的值,但该值返回为 Null。它还显示我的字典包含键和我正在寻找的值,我的 if(Items.TryGetValue(item.Key.Contains(matchKey).ToString() 返回 true 但它没有将它添加到我拥有的第二个字典中。 . 我的 Items 字典有所有的键和值,我可以返回它.. 但我试图从中提取一个键“id”及其值“80”,并添加到我的第二个字典 keyValues 和如果它包含,则返回它..
Here is the Json after Serializing
{"UserId":"","UserId2":"","id":"80"}
public Dictionary<string, string> GetKeyAndValues(string matchKey)
{
string data = JsonConvert.SerializeObject(dataEntries);
Dictionary<string, string> Items = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
Dictionary<string, string> keyValues = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> item in Items)
{
if (!Items.ContainsKey(item.Key))
{
Items.Add(item.Key.ToString(), item.Value.ToString());
}
var value = Items[matchKey];
if(Items.TryGetValue(item.Key.Contains(matchKey).ToString(), out value))
{
keyValues.Add(matchKey, value);
return keyValues;
}
}
return Items;
}
【问题讨论】:
-
欢迎来到 StackOverflow。我在您的代码中看到了几个问题,我想问您一些问题,以使您的代码对我更清楚。
dataEntries是什么?为什么不直接从中获取所需的值?为什么要把它序列化成JSON,然后把这个JSON转换成Dictionary<string, string>,然后从中获取需要的值呢? -
嗨 :),dataEntries 是一个类,我在其中持有 Json 的属性或键。UserId、UserID2 和 id。我序列化 json 的原因是我可以在字典中反序列化它。我需要字典,因为我正在对服务执行一些 HTTP 调用并将我的查询参数作为字典键/对值传递。
-
方法
GetKeyAndValues是否必须返回带有单个KeyValuePair的Dictionary?或者它可以返回KeyValuePair而不是Dictionary?您是否考虑使用Reflection通过其键找到所需的值,而不是使用当前算法ToJson -> ToDictionary -> FindValue? -
可以使用的方法如下。使用
Reflection查找matchKey所需的属性并获取其值。然后用一个KeyValuePair创建Dictionary并返回它。 -
是的,它必须返回一个字典,因为将此字典应用为我的 queryParameter,因为我的 queryParameter 接受字典。您能否以这种方式显示此反射的用法示例..
标签: c# json api dictionary serialization