theymeleaf inline javascript framework issue

狂风中的少年 提交于 2019-12-10 23:38:49

问题


<script th:inline="javascript" type="text/javascript">
    //expose list data to javascript
    var listObject = /*[[${listObject}]]*/ [];
</script>

the replacement text printed into the file is different than what Jackson library's ObjectMapper does.

With Thymeleaf in above example, listObject will be

{
   "dataType":{
      "$type":"DataType",
      "$name":"STRING"
   },
   "friendlyName":"Customer Key"
}

If I print the object with ObjectMapper(which is also used with Spring @RequestBody/@ResponseBody), it will be

{
   "dataType":"STRING",
   "friendlyName":"Customer Key"
}

Is there a way I can force thymeleaf to be compatible with ObjectMapper.


回答1:


I think this has to say something about Jackson and JSON inlining in thymeleaf.
To summarize, the possibility to switch to custom TextInliners is considered for 3.0 thymeleaf milestone.

So, currently there is no "clean" way to switch to Jackson json serialization.

What you can do however, is sneak your own TextInliner. That is:

  1. Create a class org.thymeleaf.standard.inliner.StandardJavaScriptTextInliner.
  2. Implement your own version of formatEvaluationResult(Object) method,
    where you can call the Jackson ObjectMapper .
  3. Put this new StandardJavaScriptTextInliner class in a proper place, so that it is loaded before the original class (f.e. in tomcat put it in classes dir under correct package structure).



回答2:


Another option:

when you set listObject in the thymeleaf context, set it to the string that is obtained by converting listObject to a JSON string using Jackson

then use JS eval() or the better method - JSON.parse to convert the string into a JS object.



来源:https://stackoverflow.com/questions/18318964/theymeleaf-inline-javascript-framework-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!