CodenameOne的PropertyIndex.toJSON()无法正确生成对象列表JSON如何解决
解决方案
你可以选择任意一种写法实现列表元素的正常序列化:
写法1:复用原有Property类,补充元素类型参数
在构造参数中同时传入列表类型List.class和元素类型EventItinerary.class即可,完整属性定义如下:
public final Property<List<EventItinerary>, Event> eventItineraryList = new Property<>("eventItineraryList", List.class, EventItinerary.class);
写法2:使用专用的ListProperty类(更推荐)
Codename1提供了专门处理集合类型的ListProperty类,写法更简洁直观:
public final ListProperty<EventItinerary, Event> eventItineraryList = new ListProperty<>("eventItineraryList", EventItinerary.class);
错误原因说明
- 传入
EventItinerary.class报错:你声明的属性整体类型是List<EventItinerary>,框架会将整个列表对象匹配你传入的类型参数,尝试把ArrayList强转为PropertyBusinessObject,最终触发类转换异常。 - 传入
List.class或者留空输出内存地址:框架不知道列表内部元素的类型,默认调用元素对象的toString()方法序列化,因此输出类名+内存地址的格式。
验证说明
修改完成后,序列化框架会自动识别列表元素为实现了PropertyBusinessObject的对象,遍历每个元素调用其toMapRepresentation()方法生成标准JSON结构,和EventLocation的序列化逻辑完全一致。
内容的提问来源于stack exchange,提问作者Gabriel Kazama
相关产品推荐
相关产品推荐

