[英]How to serialize a map<Integer, Custom object> with Jackson streaming API?
Say that I've got a 说我有一个
class Person {
ArrayList<MyOtherObject> lstObjects;
...
}
and then 接着
Map<Integer, Person> personMap
and want to serialize that map with Jackson Streaming API? 并希望使用Jackson Streaming API序列化该地图?
JsonGenerator g =...;
g.writeArrayFieldStart("PersonMap");
if (personMap != null) {
Iterator<Map.Entry<Integer, Person>> iter = personMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer, Person> pairs = iter.next();
Integer key = (Integer) pairs.getKey();
Person person = (Person) pairs.getValue();
g.writeNumber(key.intValue());
person.saveToFileRaw(g); // Write the object
}
}
g.writeEndArray(); // PersonMap
and person.saveToFileRaw looks like 和person.saveToFileRaw看起来像
try {
g.writeStartObject();
g.writeObjectFieldStart("Inf");
if (lstInfo != null) {
for (PersonInfo info: lstInfo)
info.saveToFileRaw(g); // Write another object
}
g.writeEndObject();
String s = PersonType.token(type);
g.writeStringField("Tp", s);
g.writeStringField("Add", address);
So the question: how to write an array/map of custom objects? 那么问题来了:如何编写自定义对象的数组/映射? g.writeStartObject() in person.saveToFileRaw throws an exception saying that it expects a value. person.saveToFileRaw中的g.writeStartObject()引发异常,表示期望值。
Any ideas how to do this? 任何想法如何做到这一点?
If you get an exception from JsonGenerator calls, you are trying to create invalid JSON structure; 如果您从JsonGenerator调用中获得异常,则您正在尝试创建无效的JSON结构; something that could not be parsed. 无法解析的内容。
One problem I see in the code is that you first call "g.writeObjectFieldStart("Inf")", but then in loop try to call method which starts with "g.writeStartObject" -- essentially trying write start-object marker "{" twice. 我在代码中看到的一个问题是,您首先调用“ g.writeObjectFieldStart(“ Inf”)“,然后在循环中尝试调用以” g.writeStartObject“开头的方法-本质上是尝试写起始对象标记” { ”两次。
You can also call "writeFieldName" separately (instead of writeObjectFieldStart()) which you probably need to do. 您也可以单独调用“ writeFieldName”(而不是writeObjectFieldStart()),而这可能是您需要做的。 Or maybe you need to do writeStartArray(() / writeEndArray() for PersonInfo entries; this depends on what exact output you want. 也许您需要为PersonInfo条目执行writeStartArray(()/ writeEndArray();这取决于您想要的确切输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.