我found an answer与此问题类似,但在发布JSON数据时无效。我有以下内容:
public class WebAppInterface {
Activity mContext;
public WebAppInterface(Activity c) {
mContext = c;
}
@JavascriptInterface
public void getURL(final String url) {
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
//do your scheme with variable "url" in UIThread side. Over here you can call any method inside your activity/fragment
}
});
}
}
我知道在通过调试进行绑定时会访问代码,但是当我传入数据时:
@ControllerAdvice
public class ControllerConfig {
@InitBinder
public void initBinder ( WebDataBinder binder ) {
StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);
binder.registerCustomEditor(String.class, stringtrimmer);
}
}
{ "companyId": " ABC "}
实际上并未在绑定期间进行修剪。我的猜测是,这只适用于请求参数而不是原始JSON主体,但不确定。如果是这样的话,我能做些类似的事情吗?
答案 0 :(得分:0)
创建此JsonDeserializer
public class WhiteSpaceRemovalDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt) {
// This is where you can deserialize your value the way you want.
// Don't know if the following expression is correct, this is just an idea.
return jp.getCurrentToken().asText().trim();
}
}
并将其设置为您的财产
@JsonDeserialize(using=WhiteSpaceRemovalSerializer.class)
public void setAString(String aString) {
// body
}
答案 1 :(得分:-1)
尝试一下, 创建一个类。 用@JsonComponent注释类 扩展JsonDeserializer 然后,在覆盖方法中添加修剪逻辑,
这将自动修剪json请求中的空格,当它碰到控制器时,不需要外部属性即可激活它。
@JsonComponent
public class WhiteSpaceRemover extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser arg0, DeserializationContext arg1)
throws IOException, JsonProcessingException {
return arg0.getValueAsString().trim();
}
}