如何用空白字段反序列化json?

时间:2021-08-17 00:57:31

I have a json string like this:

我有一个像这样的json字符串:

[{
      "_id": "abcd",
      "name": "bender rodriguez",
      "meta": {
        "location": {}
      },
      dob": ,
}
]

The section after dob blows up:

dob之后的部分爆炸:

return new JavaScriptSerializer().Deserialize<T>(json);

The problem is the empty dob. I cannot seem to find any method to handle something like this. Doesn't even seem to be a common problem? I'm not too familiar with deserializing json, what methods can I use to deal with this other than string.replace(": ,"," : null,")?

问题是空的dob。我似乎无法找到任何方法来处理这样的事情。甚至似乎不是一个常见的问题?我不太熟悉反序列化json,除了string.replace(“:,”,“:null,”)之外,我可以使用哪些方法来处理这个问题?

1 个解决方案

#1


1  

The JSON deserialiser you're using is fine, the JSON you're trying to deserialice is wrong, it's missing a value, and the initial double quotes for the dob property.

您正在使用的JSON反序列化器很好,您尝试deserialice的JSON是错误的,它缺少一个值,以及dob属性的初始双引号。

Use JSONLint to validate JSON. If that JSON is coming from a component you control, then use a JSON serializer to serialize it properly, if not, you can fix that particular problem using this:

使用JSONLint验证JSON。如果JSON来自您控制的组件,那么使用JSON序列化程序正确地序列化它,如果没有,您可以使用以下方法修复该特定问题:

string myJson = "[{ \"_id\": \"abcd\", \"name\": \"bender rodriguez\", \"meta\": { \"location\": {} }, dob\": , } ]";

JavaScriptSerializer().Deserialize(myJson.Replace("dob\": ", "\"dob\": \"\""));

But if the data changes and it keeps having an invalid JSON format, there's little you can do about it but asking whoever did that component to send you valid JSON data.

但是,如果数据发生变化并且它仍然保持无效的JSON格式,那么你可以做很少的事情,但要求那个组件的任何人发送有效的JSON数据。

#1


1  

The JSON deserialiser you're using is fine, the JSON you're trying to deserialice is wrong, it's missing a value, and the initial double quotes for the dob property.

您正在使用的JSON反序列化器很好,您尝试deserialice的JSON是错误的,它缺少一个值,以及dob属性的初始双引号。

Use JSONLint to validate JSON. If that JSON is coming from a component you control, then use a JSON serializer to serialize it properly, if not, you can fix that particular problem using this:

使用JSONLint验证JSON。如果JSON来自您控制的组件,那么使用JSON序列化程序正确地序列化它,如果没有,您可以使用以下方法修复该特定问题:

string myJson = "[{ \"_id\": \"abcd\", \"name\": \"bender rodriguez\", \"meta\": { \"location\": {} }, dob\": , } ]";

JavaScriptSerializer().Deserialize(myJson.Replace("dob\": ", "\"dob\": \"\""));

But if the data changes and it keeps having an invalid JSON format, there's little you can do about it but asking whoever did that component to send you valid JSON data.

但是,如果数据发生变化并且它仍然保持无效的JSON格式,那么你可以做很少的事情,但要求那个组件的任何人发送有效的JSON数据。