开发者

How to serialize a map<Integer, Custom object> with Jackson streaming API?

开发者 https://www.devze.com 2023-02-17 10:05 出处:网络
Say that I\'ve got a class Person { ArrayList<MyOtherObject> lstObjects; ... } and then Map<Integer, Person> personMap

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?

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

try {
            g.writeStartObject();

            g.writeObjectFieldStart("Inf");
            开发者_C百科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.

Any ideas how to do this?


If you get an exception from JsonGenerator calls, you are trying to create invalid JSON structure; 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.

You can also call "writeFieldName" separately (instead of writeObjectFieldStart()) which you probably need to do. Or maybe you need to do writeStartArray(() / writeEndArray() for PersonInfo entries; this depends on what exact output you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消