简体   繁体   English

C#JavaScriptSerializer反序列化变量类型字段

[英]c# JavaScriptSerializer deserialize variable type field

I am trying to deserialize JSON strings where some fields can be different. 我正在尝试反序列化某些字段可能不同的JSON字符串。 These are some of the strings I have to deserialize: 这些是我必须反序列化的一些字符串:

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

{"field1":"", "field2":""} {“ field1”:“”,“ field2”:“”}

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

{"field1":{"array":[1,2,3]},"field2":""} {“ 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. 其他人引发异常的原因很可能是因为反序列化目标数据类型期望在field1和field2内部有一个对象,但是在最后三个中,您有空字符串。

Try replacing the empty strings with just null . 尝试将空字符串替换为null

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

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