Search code examples
javajsonjacksonterminate

Java program terminating after ObjectMapper.writeValue(System.out, responseData) - Jackson Library


I'm using the Jackson library to create JSON objects, but when I use the mapper.writeValue(System.out, responseData) function, the program terminates. Here is my code:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

    public static void main(String[] args){
        new Test().test();
    }

    public void test() {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> responseData = new HashMap<String, Object>();

        responseData.put("id", 1);

        try {
            mapper.writeValue(System.out, responseData);
            System.out.println("done");
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }.

}

After this executes, the console shows {"id":1}, but does not show "done".


Solution

  • The problem is with the Jackson implementation, as ObjectMapper._configAndWriteValue calls UtfGenerator.close(), which calls PrintStream.close().

    I'd log an issue at https://jira.codehaus.org/browse/JACKSON

    To change the default behavior of target being closed you can do the following:

    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);