1

I use Jackson library to generate json string like this:

ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(model);

and this snipped code for instance generate somtething like this:

{"x" : "This is x", "y" : "This is y"}

but I want to generate something like this:

{'x' : 'This is x', 'y' : 'This is y'}

I mean how can I change the double quote string with single quote string.I try to change code like this:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
String str = objectMapper.writeValueAsString(model);

but this snipped code generate the first one. and of course I can handle this problem with replace method but I want Jackson library do this for me. How can I handle this problem?

3
  • 3
    Can I ask you why? That's not a valid JSON.. Commented Jun 9, 2013 at 11:05
  • this {"x" : "This is x", "y" : "This is y"} code place in another Json snipped code that start with double code and pass to client and I do not want to place backslash for other double code that present after it and for handle it I want to use single code instead of double code Commented Jun 9, 2013 at 14:13
  • Maybe you should handle this in another way. If you have this inside another field it's actually a property. Commented Jun 9, 2013 at 20:56

4 Answers 4

2

objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); is about allowing single quotes in deserializing (JSON to Objects), not serializing (Objects to JSON) as you want.

In serializing, the issue seems to be with Jackson 1.X's default serializer. Below is the code that Jackson uses to write the String values. As you can see, the double quotes are hard coded and thus unchangeable through configuration:

@Override
public void writeString(String text)
    throws IOException, JsonGenerationException
{
    _verifyValueWrite("write text value");
    if (text == null) {
        _writeNull();
        return;
    }
    if (_outputTail >= _outputEnd) {
        _flushBuffer();
    }
    _outputBuffer[_outputTail++] = '"'; // <----------------- opening quote
    _writeString(text);                 // <----------------- string actual value
    // And finally, closing quotes
    if (_outputTail >= _outputEnd) {
        _flushBuffer();
    }
    _outputBuffer[_outputTail++] = '"'; // <----------------- closing quote
}

To achieve what you want, there are at least two options:


1: Replace the quotes using Regex:

This is a safe approach because Jackson gives the double quotes (") already escaped (\"). All you have to do is escape the single quotes and switch the " around properties names and values:

ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(model);
System.out.println("Received.: "+str);
str = str.replaceAll("'", "\\\\'"); // escapes all ' (turns all ' into \')
str = str.replaceAll("(?<!\\\\)\"", "'"); // turns all "bla" into 'bla'
System.out.println("Converted: "+str);

Output:

Received.: {"x":"ab\"c","y":"x\"y'z","z":15,"b":true}
Converted: {'x':'ab\"c','y':'x\"y\'z','z':15,'b':true}

Or 2: User a custom JsonSerializer on every String field

Declare the custom serializer:

public class SingleQuoteStringSerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String str, JsonGenerator jGen, SerializerProvider sP)
            throws IOException, JsonProcessingException {
        str = str.replace("'", "\\'"); // turns all ' into \'
        jGen.writeRawValue("'" + str + "'"); // write surrounded by single quote
    }
}

Use it in the fields you want to single quote:

public class MyModel {
    @JsonSerialize(using = SingleQuoteStringSerializer.class)   
    private String x;
    ...

And proceed as usual (QUOTE_FIELD_NAMES == false is used to unquote the field names):

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
String str = objectMapper.writeValueAsString(model);
System.out.println("Received.: "+str);

Output:

Received.: {x:'ab"c',y:'x"y\'z',z:15,b:true}

Note: Since you seem to be wanting to embed the JSON into another, this last approach may also require escaping the "s (see x:'ab"c').

Sign up to request clarification or add additional context in comments.

Comments

1

Configure ObjectMapper in the following way:

final ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

//this may be what you need
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

2 Comments

this snipped code generate {x : "This is x", y : "This is y"} I want to have single quote instead of double quote
@Chris - I am using these both mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); still I am getting double quotes, is there any other way ?
1

Try looking into gson. It would look like this in gson. House myHouse = new House(); Gson gson = new Gson(); String json = gson.toJson(myHouse); Done...

http://code.google.com/p/google-gson/

Comments

1

As I said in the comment that's not valid JSON and it doesn't make any sense to escape it. You should handle it in a different way.

You should put that object inside a property.

I think you want to have something like

{"myString":"{\"fake json\":\"foo\"}"}

instead you should have:

{"myString":{"fake json":"foo"}}

That should be the proper way to handle this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.