使用near-duplicate-code-detector遇Json反序列化异常求助
解决near-duplicate-code-detector的JSON反序列化错误
问题背景
使用near-duplicate-code-detector工具时,未修改任何工具代码,但运行时抛出JSON反序列化异常。当前使用的JSON结构如下:
[ { 'filename': 'someFileName', 'tokens': ['a', 'bunch', 'of', 'tokens'] }, { 'filename': 'someFileName2', 'tokens': ['a', 'bunch', 'of', 'different', 'tokens'] }, ]
完整错误信息(翻译后):
未处理的异常:Newtonsoft.Json.JsonSerializationException: 无法将当前JSON数组(例如 [1,2,3])反序列化为类型“System.Collections.Generic.IDictionary`2[System.String,System.Object]”,因为该类型需要JSON对象(例如 {"name":"value"})才能正确反序列化。
要修复此错误,要么将JSON修改为JSON对象(例如 {"name":"value"}),要么将反序列化类型更改为数组或实现集合接口(例如 ICollection、IList)的类型,如可从JSON数组反序列化的List。也可以向类型添加JsonArrayAttribute以强制其从JSON数组反序列化。
路径 '',第1行,位置1。
错误原因
- JSON语法不合法:当前JSON使用单引号(
')包裹键名和字符串值,但标准JSON要求必须使用双引号("),这会导致解析失败。 - 结构不匹配:工具的反序列化逻辑预期接收JSON对象(键值对结构),但提供的是JSON数组(
[]包裹的列表结构),无法将数组转换为字典类型。
修复方案
步骤1:修正JSON语法错误
将所有单引号替换为双引号,并移除数组末尾多余的逗号:
[ { "filename": "someFileName", "tokens": ["a", "bunch", "of", "tokens"] }, { "filename": "someFileName2", "tokens": ["a", "bunch", "of", "different", "tokens"] } ]
步骤2:调整结构适配工具预期
如果工具确实需要JSON对象作为输入,可将数组包装在键值对中:
{ "files": [ { "filename": "someFileName", "tokens": ["a", "bunch", "of", "tokens"] }, { "filename": "someFileName2", "tokens": ["a", "bunch", "of", "different", "tokens"] } ] }
说明
不修改工具代码的前提下,只能通过调整JSON的语法和结构来适配工具的反序列化要求,优先修正语法错误,再根据工具输入规范调整结构。
内容的提问来源于stack exchange,提问作者Henry Burke
相关产品推荐
相关产品推荐

