Reputation: 15490
i need to trim all the String values
{
"startDate": "2015-06-29",
"endDate": "2015-07-04",
"category": "VIP ",
"name": " govind",
age: 10,
"place": " goa "
}
i am doing it by
JsonNode json = request().body().asJson();
CLassName cl = Json.fromJson(json , ClassName.class);
and trimming in setter of ClassName
suggest any other good approach because i know its not a good approach
Upvotes: 2
Views: 4368
Reputation: 11518
If you can confirm that the JSON will not have quotes within values then for better performance I'd do the trimming on the raw text rather than the parsed version:
val text = request.body.asText
// RegEx explanation:
// space followed by asterisk means any number of spaces
// backward slash escapes the following character
val trimmed = text.map(_.replaceAll(" *\" *", "\""))
import play.api.libs.json.Json
val json = Json.parse(trimmed)
Java version:
import play.api.libs.json.*;
String text = request().body().asText();
String trimmed = text.replaceAll(" *\" *", "\"");
JsValue json = Json.parse(trimmed);
Upvotes: 3
Reputation:
Try this:
public static void main(String[] args) {
String json =
"{"
+ " \"startDate\": \"2015-06-29\","
+ " \"endDate\": \"2015-07-04\","
+ " \"category\": \"VIP \","
+ " \"name\": \" govind\","
+ " age: 10,"
+ " \"place\": \" goa \""
+ "}";
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = new Gson().fromJson(json, stringStringMap);
Map<String, String> trimed = map.entrySet().stream()
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey().trim(), e.getValue().trim()))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
System.out.println(trimed);
// -> {endDate=2015-07-04, name=govind, place=goa, category=VIP, age=10, startDate=2015-06-29}
}
Upvotes: 0
Reputation: 330
but changing the setter is not the right way to do it. As you would not be able to create the complete object again(even if it is required). Either you write a seperate Trimmer class which take this object and trim it. or some function in the same class. I would prefer a trimmer class
Upvotes: 0