[java] Jackson 2.2의 ObjectMapper에서 JSON 인쇄하기

지금은 인스턴스가 org.fasterxml.jackson.databind.ObjectMapper있으며 String예쁜 JSON 을 원합니다 . Google 검색의 모든 결과는 Jackson 1.x 방식으로 이루어졌으며 2.2에서이 방법을 사용하는 적절한 비추천 방식을 찾지 못하는 것 같습니다. 이 질문에 코드가 절대적으로 필요하다고는 생각하지 않지만 지금 내가 가진 것은 다음과 같습니다.

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println("\n\n----------REQUEST-----------");
StringWriter sw = new StringWriter();
mapper.writeValue(sw, jsonObject);
// Want pretty version of sw.toString() here



답변

SerializationFeature.INDENT_OUTPUT다음 ObjectMapper과 같이 설정하여 예쁘게 인쇄 할 수 있습니다 .

mapper.enable(SerializationFeature.INDENT_OUTPUT);


답변

mkyong 에 따르면 , 마법의 주문은 JSONdefaultPrintingWriter예쁘게 인쇄하는 것입니다 .

최신 버전 :

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));

이전 버전 :

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));

총을 빨리 뛴 것 같습니다. 생성자가 pretty-printing을 지원 하는 gson을 시도 할 수 있습니다 .

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

도움이 되었기를 바랍니다…


답변

jackson API가 변경되었습니다.

new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());


답변

IDENT_OUTPUT은 나를 위해 아무것도하지 않았으며 jackson 2.2.3 jar와 함께 작동하는 완전한 대답을 제공합니다.

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}


답변

프로세스의 모든 ObjectMapper 인스턴스에 대해 기본적으로 이것을 켜려면, INDENT_OUTPUT의 기본값을 true로 설정하는 약간의 해킹이 있습니다.

val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)


답변

스프링과 잭슨 조합을 사용하는 경우 다음과 같이 할 수 있습니다. 제안 된대로 @gregwhitaker를 따르고 있지만 봄 스타일로 구현하고 있습니다.

<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="dateFormat">
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
            <property name="lenient" value="false" />
        </bean>
    </property>
    <property name="serializationInclusion">
        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
            NON_NULL
        </value>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref bean="objectMapper" />
    </property>
    <property name="targetMethod">
        <value>enable</value>
    </property>
    <property name="arguments">
        <value type="com.fasterxml.jackson.databind.SerializationFeature">
            INDENT_OUTPUT
        </value>
    </property>
</bean>


답변

이 질문을보고 다른 사람은 (아닌 객체) JSON 문자열이있는 경우에, 당신은에 넣어 수 있습니다 HashMap여전히를 얻을 ObjectMapper작업에. result변수는 JSON 문자열입니다.

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

// Pretty-print the JSON result
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}