0

I need to conver java array object to JSON, i am using jackson for this. I can only think that for every field name i have to iterate from the array which means i have to iterate the same array object for each field. Is there any efficient way of doing it?

        JsonGenerator jGenerator = jfactory.createJsonGenerator(out);
        jGenerator.writeStartObject();
        jGenerator.writeFieldName("images");
        jGenerator.writeStartArray();
        for(int i=0; i < topicBean.getTopicVOArray().length; i++){
            jGenerator.writeString(topicBean.getTopicVOArray()[i].getBody());
        }
        for(int i=0; i < topicBean.getTopicVOArray().length; i++){
            jGenerator.writeString(topicBean.getTopicVOArray()[i].getTopicGuid()());
        }
4

1 に答える 1

0

Depends on what you want the resulting json to look. Right now you're going to get {"images":["bodystring","bodystring","guidstring","guidstring"]} but you could also make it {"images":["bodystring","guidstring","bodystring","guidstring"]} or, even better, {"images":[{"body":"bodystring","guid":"guidstring"},{"body":"bodystring","guid":"guidstring"}]}

First solution:

for(int i=0; i < topicBean.getTopicVOArray().length; i++){
    jGenerator.writeString(topicBean.getTopicVOArray()[i].getBody());
    jGenerator.writeString(topicBean.getTopicVOArray()[i].getTopicGuid()());
}

Second solution (object wrapper):

for(int i=0; i < topicBean.getTopicVOArray().length; i++){
    jGenerator.writeStartObject();
    jGenerator.writeFieldName("body");
    jGenerator.writeString(topicBean.getTopicVOArray()[i].getBody());
    jGenerator.writeFieldName("guid");
    jGenerator.writeString(topicBean.getTopicVOArray()[i].getTopicGuid()());
    jGenerator.writeEndObject();
}
于 2012-08-30T17:33:28.337 に答える