Deserialize JSON when a value can be an object or an empty array

后端 未结 2 496
生来不讨喜
生来不讨喜 2020-12-04 03:05

I`m working with VK API. Sometimes server can return empty array instead of object, for example:

personal: [] //when it is empty

or

2条回答
  •  有刺的猬
    2020-12-04 03:27

    Instead of using try catch to switch between two possibilities, just check the first character. If it is '[', it's null, if it is '{' then you deserialize.

    EDIT:

    Now considering that the object is not the whole of the JSON, it gives me an idea: We had a similar problem with API returning inconsistent JSON serializations. In the end, we used NewtonSoft's ServiceStack.Text library (available from NuGet). We serialized to JToken objects instead of the target class. Then we processed the JToken structures to do piecemeal deserialization.

提交回复
热议问题