Results 1 to 3 of 3

Thread: Returning raw JSON String without double serializing

  1. #1
    Join Date
    Feb 2013
    Posts
    4

    Default 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. #2

    Default

    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.

  3. #3
    Join Date
    Feb 2013
    Posts
    4

    Default

    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.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •