我需要修剪所有字符串值
{
"startDate": "2015-06-29",
"endDate": "2015-07-04",
"category": "VIP ",
"name": " govind",
age: 10,
"place": " goa "
}
我是通过
来做的JsonNode json = request().body().asJson();
CLassName cl = Json.fromJson(json , ClassName.class);
并在ClassName
提出任何其他好方法,因为我知道这不是一个好方法
答案 0 :(得分:3)
如果您可以确认JSON在值中没有引号,那么为了获得更好的性能,我会对原始文本而不是解析版本进行修剪:
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版:
import play.api.libs.json.*;
String text = request().body().asText();
String trimmed = text.replaceAll(" *\" *", "\"");
JsValue json = Json.parse(trimmed);
答案 1 :(得分:0)
但更改setter并不是正确的方法。因为您无法再次创建完整对象(即使是必需的)。要么你写一个单独的修剪器类,它采取这个对象并修剪它。或同一类中的某些功能。我更喜欢修剪类
答案 2 :(得分:0)
试试这个:
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}
}