在尝试了一堆东西之后,我找到了这个解决方案。我为地图创建了一个自定义转换器。刚刚复制了 Flexjson MapTransformer 并注释掉了一个 IF 条件。下面的新代码
public class Payload {
private List<MyBean> myBeans = new ArrayList<MyBean>();
//the JSON returned has blank values for myBeans.values.items
public String toJson() {
return new JSONSerializer()
.exclude("*.class")
.include("myBeans")
.transform(new SOMapTransformer(), Map.class)
.serialize(this);
}
}
public class MyBean {
private Map<String, List<SomeBean>> items = new HashMap<String, List<SomeBean>>();
//this works
public String toJson() {
return new JSONSerializer()
.exclude("*.class")
.transform(new SOMapTransformer(), "items")
.deepSerialize(this);
}
}
这是自定义 SOMapTransformer:
import com.mycompany.mypackage.SomeBean;
import flexjson.JSONContext;
import flexjson.Path;
import flexjson.TypeContext;
import flexjson.transformer.AbstractTransformer;
import flexjson.transformer.TransformerWrapper;
public class SOMapTransformer extends AbstractTransformer {
public void transform(Object object) {
JSONContext context = getContext();
Path path = context.getPath();
Map<String, List<SomeBean>> value = (Map<String, List<SomeBean>>) object;
TypeContext typeContext = getContext().writeOpenObject();
for (Object key : value.keySet()) {
path.enqueue((String) key);
//DPD 2013-11-04: This bloody line of code cost me 12 hours. Comment it out!
// if (context.isIncluded((String) key, value.get(key))) {
TransformerWrapper transformer = (TransformerWrapper)context.getTransformer(value.get(key));
if(!transformer.isInline()) {
if (!typeContext.isFirst()) getContext().writeComma();
typeContext.setFirst(false);
getContext().writeName(key.toString());
}
typeContext.setPropertyName(key.toString());
transformer.transform(value.get(key));
// }
path.pop();
}
getContext().writeCloseObject();
}