Reputation: 8631
ObjectMapper mapper = new ObjectMapper();
searchCriteria.put(TICKET_STATUS_LIST,
mapper.writeValueAsString(ticketStatus));
String ticketListJson = mapper.writeValueAsString(tkmTicketList);
String searchCrteriaJson = mapper
.writeValueAsString(searchCriteria);
Map<String, Object> ticketSearchResult = new HashMap<String, Object>();
ticketSearchResult.put("ticketListJson", ticketListJson);
ticketSearchResult.put("searchCriteriaJson", searchCrteriaJson);
ticketSearchResult.put("count", iResultCt);
return mapper.writeValueAsString(ticketSearchResult);
I've come across this delightful code, problem is that the search criteria and ticketListJson end up being treated like strings so I get a crappy json as out:
{"count":7,"searchCriteriaJson":"{\"startRecord\":0,\"sortOrder\":\"DESC\",\"ticketStatus\":\"[\\\"Any\\\"]\",\"pageSize\":10,\"sortBy\":\"Default\",\"customer\":1599}","ticketListJson":"[{\"id\":\"30\",\"subject\":\"Test\",\"number\":\"TIC-30\",...
How can I have these inner json strings maintain their normal values without it adding a bunch of escape characters.
Upvotes: 0
Views: 54
Reputation: 159086
Don't call writeValueAsString()
more than once. Insert ticketStatus
, tkmTicketList
, and searchCriteria
into the maps directly.
ObjectMapper mapper = new ObjectMapper();
searchCriteria.put(TICKET_STATUS_LIST, ticketStatus);
Map<String, Object> ticketSearchResult = new HashMap<String, Object>();
ticketSearchResult.put("ticketListJson", tkmTicketList);
ticketSearchResult.put("searchCriteriaJson", searchCriteria);
ticketSearchResult.put("count", iResultCt);
return mapper.writeValueAsString(ticketSearchResult);
Upvotes: 1
Reputation: 133402
Just put the searchCriteria
and tkmTicketList
objects directly into the ticketSearchResult
map rather than going through the writeValueAsString
method multiple times. Jackson will walk through the Map and serialize the objects it encounters.
If you needed to do something more complicated with the serialization of those other objects, you could do this: (which I wrote first, then realised it was overkill for what you need)
Convert the searchCriteria
and tkmTicketList
to JSON tree nodes rather than strings, and then they will be included in the search result JSON rather than being re-escaped as strings:
JsonNode searchCriteriaJson = mapper.convertValue(searchCriteria, JsonNode.class)
Upvotes: 1