JSON解码时为type字段定义类型遇typeMismatch错误求解决
解决JSON中
type字段的解码类型不匹配问题 问题分析
你遇到的type字段是嵌套对象结构,内部包含ascendingSort键且对应值为空对象。类型不匹配的核心原因是你定义的类型与该嵌套结构不匹配,或未正确处理空对象的接收逻辑。
解决方案
根据type字段的结构是否固定,分两种场景处理:
场景1:type内部结构固定(仅存在ascendingSort键)
直接定义嵌套结构体,将空对象用字典/哈希表类型接收:
Python 示例
from dataclasses import dataclass import json @dataclass class SortType: ascendingSort: dict # 用dict接收空对象 @dataclass class Task: id: str markAsDoneDate: str | None endDate: float type: SortType createdAt: float # 解码执行 json_str = '''{ "id": "B2CAA3C8-077B-4A49-B5BA-206709630138", "markAsDoneDate": null, "endDate": 735025126.41189, "type": { "ascendingSort": {} }, "createdAt": 726385126.411889 }''' data = json.loads(json_str) task = Task(**data)
Go 示例
package main import ( "encoding/json" "fmt" ) type SortType struct { AscendingSort map[string]interface{} `json:"ascendingSort"` } type Task struct { ID string `json:"id"` MarkAsDoneDate interface{} `json:"markAsDoneDate"` EndDate float64 `json:"endDate"` Type SortType `json:"type"` CreatedAt float64 `json:"createdAt"` } func main() { jsonStr := `{ "id": "B2CAA3C8-077B-4A49-B5BA-206709630138", "markAsDoneDate": null, "endDate": 735025126.41189, "type": { "ascendingSort": {} }, "createdAt": 726385126.411889 }` var task Task err := json.Unmarshal([]byte(jsonStr), &task) if err != nil { fmt.Println(err) return } }
场景2:type内部结构动态(可能出现其他键,如descendingSort)
直接用字典/哈希表类型接收整个type字段,兼容所有可能的键值对:
Python 示例
from dataclasses import dataclass import json @dataclass class Task: id: str markAsDoneDate: str | None endDate: float type: dict # 用dict接收整个动态结构 createdAt: float # 解码执行 data = json.loads(json_str) task = Task(**data)
Go 示例
type Task struct { ID string `json:"id"` MarkAsDoneDate interface{} `json:"markAsDoneDate"` EndDate float64 `json:"endDate"` Type map[string]interface{} `json:"type"` // 动态接收所有键值 CreatedAt float64 `json:"createdAt"` }
核心思路
- 空对象不能用字符串、数字等基本类型接收,必须用字典/哈希表这类键值对类型;
- 固定结构用嵌套结构体保证类型安全,动态结构用字典兼容多变字段。
内容的提问来源于stack exchange,提问作者SM Arif Ahmed
相关产品推荐
相关产品推荐

