Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 569
gsingh2011 Avatar asked Dec 04 '11 01:12

gsingh2011


People also ask

Is ObjectMapper thread safe Jackson?

Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.

What is Jackson library in Java?

Jackson is one such Java Json library used for parsing and generating Json files. It has built in Object Mapper class which parses json files and deserializes it to custom java objects. It helps in generating json from java objects.


1 Answers

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);
like image 97
Programmer Bruce Avatar answered Sep 28 '22 19:09

Programmer Bruce