【发布时间】:2019-06-19 00:41:31
【问题描述】:
大家好,我有以下代码,我正在尝试将 "KEY" 和 "VALUE" 的默认值重命名为 "Name" 和 “价值”:
public class jsonOutputStyle
{
public string Name { get; set; }
public string Value { get; set; }
}
[Obsolete]
public string POB_CODE()
{
Dictionary<string, string> _dicts = null;
try
{
using (OracleConnection Oconn = new OracleConnection(connectionORI))
{
_dicts = Oconn.Query<KeyValuePair<string, string>>(
"SELECT " +
"POB_CODE AS Key," +
"POB_DESC AS Value " +
"FROM " +
"POB_CODE " +
"WHERE " +
"DISPLAY_SORT_ORDER >=1 " +
"AND " +
"DISPLAY_SORT_ORDER <=60",
null
)
.ToDictionary(pair => new jsonOutputStyle() {
Name = pair.Key,
Value = pair.Value
});
}
}
catch (SqlException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return JsonConvert.SerializeObject(_dicts, Formatting.None);
}
这会产生以下错误:
错误 CS0029 无法将类型
'System.Collections.Generic.Dictionary<WCF.Service.NNicsAPI.jsonOutputStyle, System.Collections.Generic.KeyValuePair<string, string>>'隐式转换为'System.Collections.Generic.Dictionary<string, string>'
因此,我不确定我需要做什么才能纠正问题,以便 json 输出如下所示:
[{"Name":"","Value":""},{"Name":"Female","Value":"F"},{"Name":"Male","Value":"M"}];
不是这样的:
[{"key":"","value":""},{"key":"Female","value":"F"},{"key":"Male","value":"M"}];
【问题讨论】:
-
_dicts有一个声明的类型。您正在尝试为其分配其他内容。该错误告诉您分配给它的对象的类型。我建议您将其声明为您要分配给它的值的类型。这是惯例:例如,如果我想要一个字符串的引用,我将变量声明为String foo;。如果我想引用一个窗口,我会将变量声明为Window foo;。如果我想引用System.Collections.Generic.Dictionary<WCF.Service.NNicsAPI.jsonOutputStyle, System.Collections.Generic.KeyValuePair<string, string>>,同样的原则也适用 -
你为什么用
ToDictionary(pair => new jsonOutputStyle(){...})而不是ToDictionary(p => p.Key, p => p.Value)?您的查询返回KeyValuePairs 的倍数,对吗?由于您已声明您的 dict 接受string, string,如果您只想从这些KeyValuePairs 创建字典,则需要 KeySelector 和 ValueSelector。 -
@Joelius 我这样做是因为这个问题的标题 - rename key/value to Name/Value json.net output
-
啊,现在我明白了。如果到那时还没有解决,我会添加一个答案。
标签: c# json.net oracle12c dapper keyvaluepair