簡體   English   中英

為什么 JSON 漂亮打印不起作用?

[英]Why JSON pretty print is not working?

我正在嘗試做與這個問題相同的事情,但我已經嘗試了我發現的所有可能性,但我無法讓它發揮作用。

到目前為止,我有這個代碼:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
//import javax.ws.rs.core.MediaType;

import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures;

@Path(value = "/mock")
@Controller
public class MockController {

    @BadgerFish
    @GET
    @Path(value = "/get")
    @Produces(MediaType.APPLICATION_JSON_VALUE)
    @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
    public Container getMockedContainer() {
        return newContainer();
    }

    @BadgerFish
    @GET
    @Path(value = "/getXML")
    @Produces(value = MediaType.APPLICATION_XML_VALUE)
    public Container getMockedContainerXML() {
        return newContainer();
    }

    //MORE CODE HERE
}

我可以訪問http://localhost:8081/containerMocked/mock/getXML/並輕松獲得預期的 XML 輸出。 但是當我嘗試localhost/.../get/我得到了正確的數據,但打印得並不漂亮。

至少對我來說, @JacksonFeatures(serializationEnable = { SerializationFeature.INDENT_OUTPUT}) @Produces(MediaType.APPLICATION_JSON)@JacksonFeatures(serializationEnable = { SerializationFeature.INDENT_OUTPUT})應該足夠了。

我究竟做錯了什么?

免責聲明:我不會把newContainer()作用放在這里,因為它涉及太多的類。 你必須明白的是,這個Main

public static void main(String[] args) throws javax.xml.bind.JAXBException {
    Container container = new MockController().newContainer();
    final javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext.newInstance(Container.class);
    javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(container, System.out);
}

將輸出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<container>
    <leaf>
        <id>int32</id>
        <possibleValues/>
        <type>int32</type>
        <value>2147483647</value>
    </leaf>
    <id>device</id>
</container>

並且http://localhost:8081/containerMocked/mock/get/將輸出:

{"container":{"leaf":{"id":{"$":"int32"},"possibleValues":{},"type":{"$":"int32"},"value":{"$":"2147483647"}},"id":{"$":"device"}}}

編輯:我剛剛根據此鏈接測試了@Formatted注釋,但我也沒有得到任何結果。

為什么這些注釋不起作用,但例如@Produces@BadgerFish正常工作?

如果可能,我更願意以最簡單的方式進行。 對我來說,最簡單的方法是使上述注釋之一按預期工作。

您可以嘗試使用 JAX-RS 實現注冊 ObjectMapper 提供程序:

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    @Override
    public ObjectMapper getContext(Class<?> aClass) {
        return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM