【问题标题】:.ToDictionary KeyValuePair rename key/value to Name/Value json.net output.ToDictionary KeyValuePair 将键/值重命名为名称/值 json.net 输出
【发布时间】: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&lt;WCF.Service.NNicsAPI.jsonOutputStyle, System.Collections.Generic.KeyValuePair&lt;string, string&gt;&gt;' 隐式转换为 'System.Collections.Generic.Dictionary&lt;string, string&gt;'

因此,我不确定我需要做什么才能纠正问题,以便 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&lt;WCF.Service.NNicsAPI.jsonOutputStyle, System.Collections.Generic.KeyValuePair&lt;string, string&gt;&gt;,同样的原则也适用
  • 你为什么用ToDictionary(pair =&gt; new jsonOutputStyle(){...})而不是ToDictionary(p =&gt; p.Key, p =&gt; 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


【解决方案1】:

试试这个:

_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 => pair.Key, pair => pair.Value);

我不明白您为什么要将“Key”命名为“Name”。当字典转换为 JSON 时,它看起来像这样 {"actual_value_of_key" : "value"}。您不会看到写入的变量名称。

编辑:如果您想要像 [{"Name":"","Value":""},{"Name":"Female","Value":"F"},{"Name":"Male","Value":"M"}] 这样的 JSON 输出,请不要使用字典。使用您定义的类。

_dicts = Oconn.Query<jsonOutputStyle>(
                            "SELECT " +
                                "POB_CODE AS Name," +
                                "POB_DESC AS Value " +
                            "FROM " +
                                "POB_CODE " +
                            "WHERE " +
                                "DISPLAY_SORT_ORDER >=1 " +
                            "AND " +
                                "DISPLAY_SORT_ORDER <=60",
                            null
                          )
                   .ToList();

编辑、更正 SQL

【讨论】:

    【解决方案2】:

    将它们添加到字典时不需要转换它们。您想要做的是像往常一样填充字典(使用键和值选择器),然后在序列化之前,将其更改为您的类型列表,然后定义它的序列化方式。

    试试看:

    [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(p => p.Key, p => p.Value);
            }
        }
        catch (SqlException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    
        jsonOutputStyle[] styledDictionary = _dicts.Select(p => new jsonOutputStyle() { Name = p.Key, Value = p.Value }).ToArray();
        return JsonConvert.SerializeObject(styledDictionary, Formatting.None);
    }
    

    重要变化的细分:

    .ToDictionary(p => p.Key, p => p.Value);
    

    而不是

    .ToDictionary(pair => new jsonOutputStyle() { 
       Name = pair.Key, 
       Value = pair.Value
    });
    

    这里我们首先需要得到一个简单的字典,以string为键,string为值。我们通过使用两个选择器来做到这一点。一个用于键 (p =&gt; p.Key),一个用于值 (p =&gt; p.Value)。我们还不需要担心序列化。

    现在对于序列化,我们不直接序列化字典,而是将字典转换为您的 tupel 类型的数组。这允许我们序列化在该类中定义的名称,而不是预定义的属性名称。

    jsonOutputStyle[] styledDictionary = _dicts.Select(p => new jsonOutputStyle() { Name = p.Key, Value = p.Value }).ToArray();
    return JsonConvert.SerializeObject(styledDictionary, Formatting.None);
    

    另外,right here 是一个非常相似的问题的答案,它基本上与我刚刚向您展示的事情相同。

    对于任何想知道当您序列化YourTupel[] vs Dictionary&lt;string, string&gt; vs List&lt;KeyValuePair&lt;string, string&gt;&gt; 时会发生什么的人:

    Serialized ArrayOfYourType:
    [{"Name":"Key 0","Value":"Value 0"},{"Name":"Key 1","Value":"Value 1"}]
    
    Serialized Dictionary:
    {"Key 0":"Value 0","Key 1":"Value 1"}
    
    Serialized List:
    [{"Key":"Key 0","Value":"Value 0"},{"Key":"Key 1","Value":"Value 1"}]
    

    编辑:
    我假设您需要字典(例如检查键是否不同或类似的东西)。如果您根本不需要字典,则可以直接转换数组,而无需对字典进行任何操作。

    代码如下所示:
    附言。 this answer 中的编辑使用简洁的功能使其更加干净,去看看吧。

    [Obsolete]
    public string POB_CODE()
    {
        jsonOutputStyle[] styledDictionary = 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
                                )
                        .Select(p => new jsonOutputStyle() { Name = p.Key, Value = p.Value }).ToArray();
            }
        }
        catch (SqlException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    
        return JsonConvert.SerializeObject(styledDictionary, Formatting.None);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2019-07-22
      相关资源
      最近更新 更多