简体   繁体   中英

When using servicestack deserializationToString to a DTO array, a null object is at the end of the list

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

Manipulating the input values for \\r\\n etc. becomes dicey. also, afaik, JsConfig doesn't involve a setting to ignore null values on deserialization.

the best available option is to just ignore null Rows in the post-deserialized values.

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

not the most elegant, but under the conditions, should do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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