本文介绍了Jax-rs json相当不错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用

  @Produces(application / json)
$ c>

注释输出未形成人类可读形式。我如何实现这一目标?

解决方案

在项目的任何位置创建此类。它将在部署时加载。注意 .configure(SerializationConfig.Feature.INDENT_OUTPUT,true); ,它配置映射器以格式化输出。



对于Jackson 2.0及更高版本,用以下代码替换两个 .configure()行:
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,false)
.configure(SerializationFeature.INDENT_OUTPUT,true);



相应地改变你的进口。

  package com.secret; 

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/ **
*
* @author secret
* /
@Provider
@Produces(MediaType.APPLICATION_JSON)
公共类JacksonContextResolver实现ContextResolver< ObjectMapper> {
private ObjectMapper objectMapper;

public JacksonContextResolver()抛出异常{
this.objectMapper = new ObjectMapper();
this.objectMapper
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false)
.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
}

@Override
public ObjectMapper getContext(Class<?> objectType){
return objectMapper;
}
}

请记住格式化对性能有负面影响。


in Java when i use the

@Produces("application/json")

annotation the output is not formated into human readable form. How do i achive that?

解决方案

Create this class anywhere in your project. It will be loaded on deployment. Notice the .configure(SerializationConfig.Feature.INDENT_OUTPUT, true); which configures the mapper to format the output.

For Jackson 2.0 and later, replace the two .configure() lines with these: .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(SerializationFeature.INDENT_OUTPUT, true);

And change your imports accordingly.

package com.secret;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 *
 * @author secret
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
    private ObjectMapper objectMapper;

    public JacksonContextResolver() throws Exception {
        this.objectMapper = new ObjectMapper();
    this.objectMapper
        .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
    }

    @Override
    public ObjectMapper getContext(Class<?> objectType) {
        return objectMapper;
    }
}

Bear in mind that formatting has a negative effect on performance.

这篇关于Jax-rs json相当不错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:24