如何使用c#检测到包含尾随逗号的无效JSON? [英] How can I detect invalid JSON containing a trailing comma with c#?

查看:142
本文介绍了如何使用c#检测到包含尾随逗号的无效JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,是的,我知道有无数关于检测无效Json的帖子.他们都说相同的话:尝试解析或反序列化对象.你猜怎么了?在这种情况下,Json.NET会愉快地解析我格式错误的JSON,并且不会抱怨.我认为我需要澄清一下:JSON唯一的问题是数组中的尾部逗号.以下说明了我的问题:

Yes, yes, I know that there are countless posts about detecting invalid Json. They all say the same thing: Try parsing or de-serializing the object. Guess what? In this case, Json.NET happily parses my malformed JSON and doens't complain. I think that I need to clarify: The only thing wrong with my JSON is a trailing comma in an array. The following illustrates my problem:

string badJson = "{ 'array' : [ {'objName1' : 'value1'}, {'objName2' : 'value2'}, {'objName3' : 'value3'}, ] }";

var obj = JObject.Parse(badJson);

JSON在浏览器中无效,因为它在数组中有逗号结尾,但是很高兴将其解析为jobject.由于我实际上无法使用序列化来检测此问题,因此该怎么办?

The JSON isn't valid in a browser as it has a trailing comma in the array, but it's happily parsed into a jobject. Since I can't actually use serialization to detect this problem, how can I?

请注意,我尝试序列化为一个对象,该对象产生了相同的结果.

Note that I've tried serializing into an object, that produced the same result.

更新:

下面的代码将正确检测逗号并将其删除,以防万一有人需要这样做:

The following code will detect the comma correctly and strip it, in case anyone needs to do this:

var regex = new Regex(@"(.*?),\s*(\}|\])",(RegexOptions.Multiline));

var cleanJson = regex.Replace(content, m => String.Format("{0} {1}",m.Groups[1].Value,m.Groups[2].Value));

另一种可能的解决方案是将.NET Json解析器与我的对象模型一起使用.对我有用的另一种解决方案是将对象解析为Jobject,然后再次对其进行序列化.这使我可以在需要的地方使用Json.这比上面的正则表达式要慢得多,所以我最终使用了正则表达式.

Another possible solution would be to use the .NET Json parser with my object model. Another solution that worked for me was to parse the object into a Jobject then serialize it again. That allowed me to use the Json where I needed to. This was much slower than the above regex, so I ultimately used the regex.

推荐答案

if Regex.IsMatch(badJson, "^.*,\s*]\s*}$") 
   throw new Exception("hey that's bad json");

这篇关于如何使用c#检测到包含尾随逗号的无效JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆