source

Jackson 2.2의 Object Mapper에서 JSON을 예쁘게 인쇄했습니다.

goodcode 2022. 9. 3. 13:16
반응형

Jackson 2.2의 Object Mapper에서 JSON을 예쁘게 인쇄했습니다.

지금 이 순간에는org.fasterxml.jackson.databind.ObjectMapper그리고 나는 그것을 받고 싶다.String예쁜 JSON이랑.구글 검색 결과 모두 잭슨 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_OUTPUTObjectMapper다음과 같이 합니다.

mapper.enable(SerializationFeature.INDENT_OUTPUT);

mkyong에 따르면 마법 주문은defaultPrintingWriterJSON을 예쁘게 인쇄하려면:

새로운 버전:

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

이전 버전:

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

내가 좀 성급한 것 같아.컨스트럭터가 예쁜 인쇄를 지원하는 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 jars와 함께 작동하는 완전한 답변을 주었다.

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 인스턴스에 대해 기본적으로 이 기능을 켜려면 다음과 같은 간단한 해킹을 통해 INDEC_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일하기 위해.resultvariable은 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();
} 

이거 먹어봐.

 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

언급URL : https://stackoverflow.com/questions/17617370/pretty-printing-json-from-jackson-2-2s-objectmapper

반응형