-2
class Foo {
  String name = "Bar";
}

Serialising the above object using ObjectMapper().convertValue(foo, JsonNode::class) will return JSON object as:

{
  "name": "Bar"
}

my desired result however is:

{
  name: "Bar"
}  

I have tried a custom serialiser but it always writes keys as strings. Is there a way to serialise my POJO in this format using Jackson or any of it's annotation to avoid a substituting chars or building the string my self.

Sterling Duchess
  • 1,970
  • 16
  • 51
  • 91
  • So is the definition of JSON: https://de.wikipedia.org/wiki/JavaScript_Object_Notation How to parse this can be read here: https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – nologin Mar 28 '19 at 19:56
  • 2
    Your desired result isn't valid JSON. Are you attempting to produce JSON, or something JSON-like? – Makoto Mar 28 '19 at 19:57
  • @Makoto JSON-like as JavaScript object. – Sterling Duchess Mar 28 '19 at 20:22
  • Remember - you can't have a JavaScript object with invalid JSON, so I'll state it once more - is this going to be something which is JSON-like (and you deal with the fact that it isn't valid on your side), or are you feeding this to something else (like a JavaScript app) which would reasonably expect valid JSON? – Makoto Mar 28 '19 at 20:28
  • I generate this as a javascript object and pass it using `application/javascript` content type. This is injected in JS frontend app. – Sterling Duchess Mar 28 '19 at 20:36

1 Answers1

2

Beside the fact that your "JSON" will not be valid anymore you can disable JsonGenerator.Feature.QUOTE_FIELD_NAMES in your ObjectMapper.

ObjectMapper mapper = new ObjectMapper()
        .disable(JsonGenerator.Feature.QUOTE_FIELD_NAMES);

The result of mapper.writeValueAsString(new Foo()) will be:

{name:"Bar"}

To enable pretty print you can use either:

ObjectMapper mapper = new ObjectMapper()
        .disable(JsonGenerator.Feature.QUOTE_FIELD_NAMES)
        .enable(SerializationFeature.INDENT_OUTPUT);

Or use this in the output step:

String result = mapper
        .writerWithDefaultPrettyPrinter()
        .writeValueAsString(new Foo());

The result in both cases will be:

{
  name : "Bar"
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • 1
    this is exactly what I was looking for I'm aware it breaks JSON validity but it's not exactly going to be JSON it's injected on frontend as JS Object which can have non-quoted field names. Thank you very much. – Sterling Duchess Mar 28 '19 at 21:09
  • Sorry it works it was loading response from cache. Thanks for the help. – Sterling Duchess Mar 28 '19 at 21:38