【问题标题】:JsonConvert.SerializeObject and handling of Empty StringsJsonConvert.SerializeObject 和空字符串的处理
【发布时间】:2014-04-02 18:02:48
【问题描述】:

我有一个从包含空字符串的 Web 服务返回的对象。该对象称为Docs,对象Docs.RowsList<List<string>>,然后在下面的代码中用作filteredRows。当我使用JsonConvert.SerializeObject 时,它会删除每个具有空字符串的列。这些列很重要。

我尝试了这两种方法:

JsonConvert.SerializeObject(filteredRows,
    Formatting.Indented,
    new JsonSerializerSettings { });

JsonConvert.SerializeObject(filteredRows,
    Formatting.Indented,
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });

所有带有空字符串的列仍在被删除。我如何让它保留它们?

filteredRows 也被定义为List<List<string>>。我可以将其序列化为定义的对象吗?

【问题讨论】:

    标签: c# serialization json.net


    【解决方案1】:

    您能否提供一个演示该问题的示例程序?像下面这样的简单示例似乎可以正常工作。在序列化过程中不会删除 null 和空字符串。是否是您的过滤过程实际上正在删除这些值?

    class Program
    {
        static void Main(string[] args)
        {
            List<List<string>> rows = new List<List<string>>
            {
                new List<string>
                {
                    "A",
                    null,
                    ""
                },
                new List<string>
                {
                    null,
                    "B",
                    ""
                },
                new List<string>
                {
                    "",
                    null,
                    "C"
                }
            };
    
            string json = JsonConvert.SerializeObject(rows);
            Console.WriteLine(json);
        }
    }
    

    输出:

    [["A",null,""],[null,"B",""],["",null,"C"]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多