gson 在Java中使JSON漂亮的最佳方法

bqujaahr  于 7个月前  发布在  Java
关注(0)|答案(6)|浏览(80)

我有一个返回如下格式的对象列表(不漂亮)。

{"data":[{"id":1,"firstName":"Bill","lastName":"Johnson"}]

字符串
我希望它能像这样(漂亮)。

{
    "data":[{
        "id":1,"
        firstName":"Bill",
        "lastName":"Johnson"
        }]
}


这是我的方法签名,沿着我对服务的调用以查询DB和将JSON打印到屏幕的返回。

public @ResponseBody ResponseEntity<ResponseData<List<NameSearchDTO>>> getInfo(@PathVariable String code, @PathVariable String idType)

ResponseData<List<NameSearchDTO>> response = new ResponseData<>();

List<NameSearchDTO> results = officeService.getByCode(code, idType); 
if (!results.isEmpty()) {
            response.setData(results);
            response.setStatus(Enum.SUCCESS.getDescription());
            response.setMessage(Enum.STATUS_SUCCESS.getDescription());
return new ResponseEntity<>(response, HttpStatus.OK);
}


ResponseData类实现了Serializable。如果我没有使用Jackson或任何其他JSON库,这是否使它成为“真”JSON?
如何将响应传递给下面的ObjectMapper以使其美观?

ObjectMapper jacksonMapper = new ObjectMapper();
jacksonMapper.configure(SerializationFeature.INDENT_OUTPUT, true);


或者我需要创建某种JSONHelper类?
ResponseData类

public class ResponseData <E> implements Serializable{

    private E data;
    private String status;
    private String message;
    private boolean hasValidationError = false;

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean getHasValidationError(){
        return hasValidationError;
    }

    public void setHasValidationError(boolean hasValidationError){
        this.hasValidationError = hasValidationError;
    }
}

mlnl4t2r

mlnl4t2r1#

我认为美化json字符串的最好方法是使用Jackson:

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject)

字符串

voase2hg

voase2hg2#

您可以定义

  • a MappingJacksonHttpMessageConverter(不需要Sping Boot )
  • 一个Jackson2ObjectMapperBuilder Bean
  • @Primary注解的简单ObjectMapper Bean
  • 配置属性(Sping Boot -跳到这个最简单)。

对于第一个解决方案,您需要实现WebMvcConfigurer接口
(skip这一个,如果你在Spring Boot )

@Configuration
class CustomWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
        final ObjectMapper mapper =
                new Jackson2ObjectMapperBuilder()
                        .indentOutput(true)
                        .build();

        // Or build ObjectMapper without the Spring builder, it's the same thing
        converters.add(new MappingJackson2HttpMessageConverter(mapper));
    }
}

字符串
关键是这条线

indentOutput(true)


它实际上操作底层的ObjectMapper配置。

public Jackson2ObjectMapperBuilder indentOutput(boolean indentOutput) {
    this.features.put(SerializationFeature.INDENT_OUTPUT, indentOutput);
    return this;
}


第二个简单一点

@Bean
Jackson2ObjectMapperBuilder jackson() {
   return new Jackson2ObjectMapperBuilder().indentOutput(true);
}


第三个更简单,

@Bean
@Primary
ObjectMapper objectMapper() {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.enable(SerializationFeature.INDENT_OUTPUT);  
   return mapper;
}


第四种方法只包括使用configuration属性

spring.jackson.serialization.indent_output=true

fhity93d

fhity93d3#

我相信你正在寻找Gson的漂亮打印功能。因为你已经用gson标记了你的问题,我想如果你使用库,那就没问题了。Mkyong有一个关于漂亮打印Here的很棒的教程。
本教程的基本内容是:

Gson gson = new GsonBuilder().setPrettyPrinting().create();

字符串

wtzytmuj

wtzytmuj4#

不需要导入一堆新的东西。只有系统可能会抱怨(如果有的话)。但如果你已经在使用Jackson,并希望使用Map器->只需使用“readValue”或“writeValue”的权利?
此链接解释了很多方法来做到这一点:Jackson Examples
删除结果赋值并使用Mapper进行直接转换

ObjectMapper jacksonMapper = new ObjectMapper();
jacksonMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
List<NameSearchDTO> mappedResults = mapper.readValue(officeService.getByCode(code, idType) ,new TypeReference<List<NameSearchDTO>>() {} );

字符串
然后将其添加到结果返回中。(添加容器类似乎有点笨拙,但我不假装知道您的要求)。

if (!mappedResults.isEmpty()) {
            response.setData(mappedResults);
            response.setStatus(Enum.SUCCESS.getDescription());
            response.setMessage(Enum.STATUS_SUCCESS.getDescription());
return new ResponseEntity<>(response, HttpStatus.OK);

ubbxdtey

ubbxdtey5#

您标记了gson,因此您可以使用此库来显示.json文件:
import org.json.JSONObject

val json = "{\"data\":[{\"id\":1,\"firstName\":\"Bill\",\"lastName\":\"Johnson\"}]\n"

val jsonObject = JSONObject(json)

println(jsonObject.toString(4))

字符串
https://github.com/google/gson

gab6jxml

gab6jxml6#

可以从JSONObject使用toString(int indentFactor)

相关问题