简体   繁体   English

JsonConvert.SerializeObject 和处理空字符串

[英]JsonConvert.SerializeObject and handling of Empty Strings

I have an object that is returned from a web service containing empty strings.我有一个从包含空字符串的 Web 服务返回的对象。 The object is called Docs and the object Docs.Rows is a List<List<string>> which is then used in the code below as filteredRows .该对象被称为Docs和对象Docs.Rows是一个List<List<string>>然后将其在代码中使用下面作为filteredRows When I use JsonConvert.SerializeObject , it removes every column that has an empty string.当我使用JsonConvert.SerializeObject ,它会删除每个包含空字符串的列。 These columns are important.这些列很重要。

I've tried these 2 approaches:我试过这两种方法:

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

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

All columns with empty strings are still being removed.所有带有空字符串的列仍被删除。 How do I make it keep them?我如何让它保留它们?

The filteredRows is also defined as List<List<string>> . FilteredRows 也定义为List<List<string>> Can I serialize that into a defined object?我可以将其序列化为定义的对象吗?

Can you provide an example program that demonstrates the problem?你能提供一个示例程序来演示这个问题吗? A simple example like the following seems to work fine.像下面这样的简单示例似乎工作正常。 Neither null nor empty strings are removed during serialization.序列化期间既不会删除空字符串也不会删除空字符串。 Could it be your filtering process that is actually removing the values?是否是您的过滤过程实际上正在删除这些值?

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);
    }
}

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM