0

I am coding in C# on Visual Studio 2013 and I'm trying to deserialize some JSON using ServiceStack 3.9.71. They are contained in files (not under my control) and when I try to deserialize it, I end up with the correct array of DTO's but in addition, I have a null object at the end of the array. I've narrowed it to a carriage return ("\r") at the end of the file. A few solutions I can do is to trim the string, or remove all the "\r", or disable CRLF auto switch in GIT and just be super diligent when committing, however, I feel that seems like a "hack". I feel that DeserializeFromString should be able to handle carriage returns at the end of the string. On the brighter side, when I'm run the same code on OSX, it works perfectly fine since the file is now in Unix format that only uses linefeeds and not a combination of carriage returns and line feeds.

Has anyone else seen this? Any recommended fixes besides the ones I've mentioned?

To prove it to myself, I wrote a simple test (fails both Windows and OSX).

My DTO:

    class DeserializeTestData
    {
        public int someData { get; set; }
        public String moreData { get; set; }
    }

My Test:

    [Test]
    public void ShouldNotContainNullItemsWhenDeserializing()
    {
        var deserializeMe = "[\r\n\t{\r\n\t\t\"someData\": 1,\r\n\t\t\"moreData\": \"I'm data!\r\nokok\r\n\"\r\n\t\t},\r\n\t{\r\n\t\t\"someData\": 2,\r\n\t\t\"moreData\": \"I'm also some data!\"\r\n\t\t}\r\n]\r\n";
        var rows = ServiceStack.Text.JsonSerializer.DeserializeFromString<DeserializeTestData[]>(deserializeMe);
        foreach (var row in rows)
        {
            Assert.That(row, Is.Not.EqualTo(null));
        }
    }

The results:

Test Name:  ShouldNotContainNullItemsWhenDeserializing
Test Outcome:   Failed
Test Duration:  0:00:00.125
Result Message: 
Expected: not null
   But was:  null
4

1 回答 1

0

操作 \r\n 等的输入值变得很冒险。另外,afaik,JsConfig 不涉及在反序列化时忽略空值的设置。

最好的选择是忽略后反序列化值中的空行。

var nonNullRows = rows.Where(r => r != null).ToList();

不是最优雅的,但在有条件的情况下,应该能胜任。

于 2014-03-28T23:49:49.263 回答