Java 何时使用ObjectMapper类的writeValueAsString()方法,何时直接使用String

Java 何时使用ObjectMapper类的writeValueAsString()方法,何时直接使用String,java,spring,rest,Java,Spring,Rest,在我的项目中,有两种类型的代码: HttpEntity entity=新的HttpEntity(注释、标题) 此处注释为字符串类型,标题为HttpHeader对象 ObjectMapper om=new ObjectMapper(); HttpEntity=新的HttpEntity(om.writeValueAsString(注释),标题) 我只想知道哪一个更好,为什么。 感谢您提前提供帮助注释:请求发送到服务器 标题:注释类型json或xml、html、图像、多部分。。。等等 请参见此示例:

在我的项目中,有两种类型的代码:

  • HttpEntity entity=新的HttpEntity(注释、标题)
  • 此处注释为字符串类型,标题为HttpHeader对象

  • ObjectMapper om=new ObjectMapper();
    HttpEntity=新的HttpEntity(om.writeValueAsString(注释),标题)
  • 我只想知道哪一个更好,为什么。
    感谢您提前提供帮助

    注释:请求发送到服务器

    标题:注释类型json或xml、html、图像、多部分。。。等等

    请参见此示例:

    RestTemplate restTemplate = new RestTemplate();
        ObjectMapper mapper = new ObjectMapper();
        String requestJson = null;
        try {
            requestJson = mapper.writeValueAsString(Yourrequest);
        } catch (JsonGenerationException e) {
            LOGGER.error("JsonGenerationException occurred ", e);
    
        } catch (JsonMappingException e) {
            LOGGER.error("JsonMappingException occurred ", e);
        } catch (IOException e) {
            LOGGER.error("IOException occurred ", e);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(requestJson, headers);
        LOGGER.info("send request to  url {} ", getUrl());
        YourTypeOfResponse response = restTemplate.postForObject(URL_LOCAL,
                entity, YourTypeOfResponse.class);
    
    RestTemplate RestTemplate=new RestTemplate();
    ObjectMapper mapper=新的ObjectMapper();
    字符串requestJson=null;
    试一试{
    requestJson=mapper.writeValueAsString(您的请求);
    }捕获(JsonGenerationException e){
    LOGGER.error(“发生JsonGenerationException”,e);
    }捕获(JsonMappingException e){
    LOGGER.error(“发生JsonMappingException”,e);
    }捕获(IOE异常){
    LOGGER.error(“发生IOException”,e);
    }
    HttpHeaders=新的HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity=新的HttpEntity(requestJson,headers);
    info(“将请求发送到url{}”,getUrl());
    YourTypeOfResponse-response=restTemplate.postForObject(URL\u LOCAL,
    实体,您的响应类型。类);
    
    writeObjectAsString
    将其作为JSON格式的字符串写入。例如,如果我有一个类坐标,它看起来像:

    class Coordinate {
      private int x;
      private int y;
      // plus constructor and methods
    }
    
    然后,
    om.writeValueAsString(新坐标(1,2))
    将生成如下内容

    { "x":1,"y":2 }
    
    而不是
    toString
    方法生成的任何内容


    因此,当您的客户端需要JSON格式的字符串时,请使用
    ObjectMapper.writeValueAsString

    都不是。只需返回
    注释
    ,让spring消息转换器进行转换。