Announcement Announcement Module
Collapse
No announcement yet.
Returning raw JSON String without double serializing Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Returning raw JSON String without double serializing

    I have a db that stores JSON strings. I want a controller that just returns these JSON strings. My problem is that the strings get escaped because I have configured a messageConverter:
    Code:
    @Bean
    MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
        MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
        mappingJacksonHttpMessageConverter.setPrettyPrint(true);
        return mappingJacksonHttpMessageConverter;
    }
    So that this controller:
    Code:
     @RequestMapping(value = "test", method = RequestMethod.GET)
    public @ResponseBody
    String getTest() {
        return "{\"a\":1, \"b\":\"foo\"}";
    }
    leads to an output of "{\"a\":1, \"b\":\"foo\"}", which isn't what I want. I want the message converter there because not all of my methods are like this, many of them return objects and I like the message converters behavior.

    Is there some way to skip the message converter for certain methods? Is there an annotation / other way I can indicate that this is a raw json string I am returning? Any thoughts / suggestions for how to best tackle this would be appreciated. Thanks.

  • #2
    Hello
    try with:
    @RequestMapping(value = "/testString",method=RequestMethod.GET)
    @ResponseBody
    public ObjectNode getAandB() {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    node.put("a", "a");
    node.put("b", "b");
    return node;
    }
    It will return a response: {
    "a" : "a",
    "b" : "b"
    }.
    In your case you can read the strings from database into an object and then to serialize this object.

    Comment


    • #3
      Yeah, that does work. Seems kind of silly to deserialize just to serialize. On the other hand, its pretty fast and its far more common (in terms of number of methods) for me to want the default behavior.

      Comment

      Working...
      X