提问人:Dana 提问时间:11/10/2023 更新时间:11/10/2023 访问量:14
Flutter / Dart JSON 解码在重复的嵌套对象上失败
Flutter / Dart JSON decode failing on duplicate nested objects
问:
在我的 Flutter 应用程序中,我正在转换以下 JSON:
{
"2023-11-09": [
{
"id": 39,
"name": "Bunion Removal - Edith Davison",
"placeId": "ChIJwQhUmsO_woARfq8XEsZwfvI",
"schedule": {
"id": 9,
"serviceId": 24,
"locationDescription": "501 South Buena Vista Street, Burbank, California, 91505",
"dateTimeStart": "2023-08-28T10:00:00-07:00",
"dateTimeEnd": "2023-08-28T11:00:00-07:00",
"recurrence": "RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH"
}
},
{
"id": 43,
"name": "Bunion Removal - Alfredo Mack",
"placeId": "ChIJwQhUmsO_woARfq8XEsZwfvI",
"schedule": {
"id": 9,
"serviceId": 24,
"locationDescription": "501 South Buena Vista Street, Burbank, California, 91505",
"dateTimeStart": "2023-08-28T10:00:00-07:00",
"dateTimeEnd": "2023-08-28T11:00:00-07:00",
"recurrence": "RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH"
}
}
]
}
在 Dart/Flutter 中反序列化为对象类时,一切正常......我有一个包含 Schedule 类的 Appointment 类。通常,JSON解码器可以完美运行。
但是,在这种情况下,如果有两个具有相同计划的约会,则 Json Map 中约会的第二个实例包含一个“计划”,其中只有其 id 字段(通过调试器进行内省),从而导致反序列化 snafu。
我尝试过在 Schedule 类上使用 == / 哈希码函数 - 甚至到了总是创建唯一值(各种手段)的程度,但无济于事......我仍然会遇到以下例外,但前提是多个约会具有相同的时间表:
E/flutter (17946): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: Class 'int' has no instance method '[]'.
E/flutter (17946): Receiver: 30
E/flutter (17946): Tried calling: []("id")
E/flutter (17946): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
以下是相关的类方法:
factory Appointment.fromJSON(Map<String, dynamic> json) => Appointment (
id: json['id'],
name: json['name'],
placeId: json['placeId'],
schedule: null != json['schedule'] ? Schedule.fromJSON(json['schedule']) : null
);
和
factory Schedule.fromJSON(dynamic json) => Schedule (
id: json['id'],
serviceId: json['serviceId'],
locationDescription: json['locationDescription'],
dateTimeStart: json['dateTimeStart'],
dateTimeEnd: json['dateTimeEnd'],
recurrence: json['recurrence']
);
任何和所有的帮助都是值得赞赏的。提前致谢
答:
0赞
lou_codes
11/10/2023
#1
我唯一能感觉到错误的是参数(动态json)
尝试将其指定为 Map<String,dynamic>
factory Schedule.fromJSON(Map<String, dynamic> json) => Schedule (
id: json['id'],
serviceId: json['serviceId'],
locationDescription: json['locationDescription'],
dateTimeStart: json['dateTimeStart'],
dateTimeEnd: json['dateTimeEnd'],
recurrence: json['recurrence']
);
评论