简体   繁体   中英

c# JavaScriptSerializer deserialize variable type field

I am trying to deserialize JSON strings where some fields can be different. These are some of the strings I have to deserialize:

{"field1":{"array":[1,2,3]},"field2":{"array":["a","b","c"]}}

{"field1":"", "field2":""}

{"field1":"","field2":{"array":["a","b","c"]}}

{"field1":{"array":[1,2,3]},"field2":""}

The first string is successfully deserialized, but the remainder throws an exception.

Is it possible to parse the four strings with the same code?

The reason why the others are throwing an exception is most likely because your deserialization target data type is expecting an object inside field1 and field2, but in last three, you have empty strings.

Try replacing the empty strings with just null .

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