如何用System.Text.Json反序列化JSON字符串?遇JsonException报错
问题解决步骤
1. 修复JSON反序列化错误
错误核心原因:你提供的JSON是多个独立对象用逗号拼接,既不是单个合法JSON对象,也不是标准JSON数组(缺少[]包裹),但你却尝试反序列化为单个InstrumentData实例,导致解析器报错。
解决方法:
- 给JSON内容添加数组括号
[],将其转为合法的JSON数组; - 把反序列化目标类型改为
List<InstrumentData>,匹配JSON数组结构。
修正后的JSON示例:
[ { "Id": 4897244, "Type": "InstrumentVoltage", "Kind": "Value", "Date": "2023-01-06T17:40:14", "Status": "Official", "Value": 12.75, "Properties": { "OriginalStatus": "Official" } }, { "Id": 4897245, "Type": "BatteryPercent", "Kind": "Value", "Date": "2023-01-06T17:40:14", "Status": "Official", "Value": 99, "Properties": { "OriginalStatus": "Official" } } ]
修正后的反序列化代码:
List<InstrumentData> dataList = JsonSerializer.Deserialize<List<InstrumentData>>(jsondata, options);
2. 跳过JSON中的"Properties"字段
有三种实用方式可选:
方式一:依赖默认行为
你的InstrumentData类中没有定义Properties属性,System.Text.Json默认会自动忽略JSON中存在但类未声明的字段,无需额外配置,保持现有类结构即可。方式二:显式配置忽略未知字段
若要明确指定忽略所有类未定义的JSON字段,可修改序列化选项:JsonSerializerOptions options = new JsonSerializerOptions() { AllowTrailingCommas = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingUnknown };方式三:类中存在Properties属性时
如果后续需要保留类中的Properties属性但反序列化时跳过,给该属性添加[JsonIgnore]特性:[JsonIgnore] public object Properties { get; set; }
内容的提问来源于stack exchange,提问作者0___________
相关产品推荐
相关产品推荐

