I have a object of type:
RestConsumerRequest<RewardsAccumulationRequest>
which has @JsonProperty annotated fields like:
@JsonProperty("product_code")
private String productCode;
@JsonProperty("sub_product_code")
private String subProductCode;
when I wrote it as String using:
LOG.info("RestConsumerRequest<RewardsAccumulationRequest> is {}", objectMapper.writeValueAsString(restRequest))
I got:
..., "product_code":"CSS","sub_product_code":"SC",...
I tried removing the backslashes with:
objectMapper.writeValueAsString(restRequest).replace("\","")
the backlashes are still there.
If I use replaceAll:
LOG.info("RestConsumerRequest<RewardsAccumulationRequest> is {}", objectMapper.writeValueAsString(restRequest).replaceAll("\"", ""));
then all " are gone (without any quotes)
..., product_code:CSS,sub_product_code:SC,...
what is the proper way to remove the backslashes only, leaving properly quoted JSON? I guess there must be a smarter way to do this, such as some configuration for objectMapper.
2
Answers
I have used below code, it printed as below.
22:10:41.743 [main] INFO com.example.SpringBootDemo_3_3_0.JsonPrinting — {"product_code":"productCode","sub_product_code":"subProduct"}
public class JsonPrinting {
}
class RewardsAccumulationRequest implements Serializable {
}
You don’t actually need to remove the backslashes because they aren’t part of the JSON itself—they’re just there to escape the quotes in the string when it’s printed out. If you want to see the JSON in a more readable format without all those backslashes, you can tweak the ObjectMapper to pretty-print the JSON for you.
Here’s how you can do it:
and the output will be a prettier json :