【问题标题】:Object Initializer syntax to produce correct Json生成正确 Json 的对象初始化器语法
【发布时间】:2010-09-15 21:45:51
【问题描述】:

我正在尝试使用 linq 将数据列表调整为特定形状,以便从 ajax 调用中作为 Json 返回。

鉴于此数据:

var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");

这段代码:**这是不正确的,需要修复! **

var shaped = data.Select(c =>
    new { c = c }
).ToList();

serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();

我希望desiredResult 成为:

{
    "One": "One",
    "Two": "Two",
    "Three": "Three"
}

但目前是:

{ "c" : "One" },{ "c" : "Two" }

一个问题是在对象初始化器的左侧我想要c 的值,而不是c 本身...

【问题讨论】:

    标签: c# linq json


    【解决方案1】:

    提供的解决方案是为了正确性,而不是性能。

            List<string> data = new List<string>()
            {
                "One",
                "Two",
                "Three"
            };
    
            string result =
                "{ "
                +
                string.Join(", ", data
                  .Select(c => @"""" + c + @""": """ + c + @"""")
                  .ToArray()
                ) + " }";
    

    【讨论】:

      【解决方案2】:

      在json中,“c”中的“c”:“One”是属性名。而在 C# 世界中,您不能动态创建属性名称(忽略 System.ComponentModel)。

      基本上,我认为你不能为所欲为。

      【讨论】:

        【解决方案3】:

        使用JSON.NET 怎么样?

        【讨论】:

          【解决方案4】:

          我回答这个老问题只是因为所有其他回答基本上都是错误的或不完整的。

          JSON 真的很简单,所以基本上,要得到你想要的 JSON,你只需要掌握 JSON 数组之间的区别:

          ["one", "two", "three"]
          

          还有 JSON 对象/字典(对象和字典其实是一样的):

          {"a": "one", "b": "two", "c": 3}
          

          请注意“c”元素的类型不同,但这对于 Javascript 来说不是问题。

          鉴于此,我在 .NET 下使用的几乎每个序列化程序(几乎总是很棒的 JSON.NET 库)都将 .NET 对象或 .NET 字典转换为 JSON 对象。

          因此,您需要将 List 转换为 Dictionary,然后为序列化程序提供字典或对象。 另一个问题是为什么你想要一个值等于键的字典,但即使我很怀疑,我也会接受这一点。

          给出的例子:

          List<string> source = new List <string> () {"a", "b", "c"};
          
          Dictionary<string, string> dict = source.ToDictionary(el => el, el => el);
          
          var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
          

          jsonString 应该是"{'a':'a', 'b':'b', 'c':'c'}", 根据格式或多或少的空格

          【讨论】:

            猜你喜欢
            • 2016-10-26
            • 2010-09-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-11
            • 2013-06-27
            相关资源
            最近更新 更多