简体   繁体   English

使用 Z7930C951E609E4161E82EDZ26004 将 Java HashMap 序列化到 JSON

[英]Serliazing Java HashMap to JSON using Jackson ObjectMapper

I am developing a Spring Boot MVC application that uses Thymeleaf templates on the front end.我正在开发一个 Spring 引导 MVC 应用程序,该应用程序在前端使用 Thymeleaf 模板。

I am trying to bind a HashMap from my MVC model to a JavaScript variable in one of my Thymeleaf templates.我正在尝试将我的 MVC model 中的 HashMap 绑定到我的 Z3908B6268ACF837 之一中的 JavaScript 模板变量。 This is what has been done so far: -这是迄今为止所做的: -

  1. In my MVC controller class, I created a HashMap that represents user skills organised into categories.在我的 MVC controller class 中,我创建了一个 HashMap 代表按类别组织的用户技能。 The Skill class is a data object containing name and id properties: -技能 class 是一个数据 object 包含名称和 id 属性:-

    Map<String, List<Skill>> skillsMap = new HashMap();

  2. I populated this map with all the category and skill information and then added it to my Model: -我用所有类别和技能信息填充了这个 map,然后将其添加到我的 Model:-

    model.addAttribute("skillsMap", skillsMap);

  3. On my Thymeleaf template in a script section, I am attempting to bind this HashMap to a variable.在脚本部分的 Thymeleaf 模板上,我试图将此 HashMap 绑定到变量。 As a second step I then attempt to retrieve one of the lists from the map and assign to a second variable: -作为第二步,我尝试从 map 中检索其中一个列表并分配给第二个变量:-

    var skillsMapMap = [[${skillsMap}]];

    var adminList = skillsMapMap.get('Admin');

  4. When I debugged this, I could see that the HashMap was being read and an attempt was being made to bind it to my JavaScript variable: -当我调试它时,我可以看到正在读取 HashMap 并尝试将其绑定到我的 JavaScript 变量:-

    var skillsMapMap = {Languages=[Python, SQL, PL/SQL, Java], Databases=[MySQL, Oracle, Mongo], Editors=[Word, TextPad, Notepad]};

This looked good at first glance and I could see that it contained all my data, but it was throwing the following error: -乍一看这看起来不错,我可以看到它包含了我的所有数据,但它抛出了以下错误:-

Uncaught Syntax Error: invalid shorthand property initializer
  1. Having researched this, I realized that this error was caused because Java does not by default serialize the map in valid JSON format and so the attempted bind to a JavaScript variable failed. Having researched this, I realized that this error was caused because Java does not by default serialize the map in valid JSON format and so the attempted bind to a JavaScript variable failed. So, instead of just adding the HashMap straight to the Model as in step 2, I added some code to use Jackson to convert it into a JSON String first: - So, instead of just adding the HashMap straight to the Model as in step 2, I added some code to use Jackson to convert it into a JSON String first: -

     //Populate the map with all required data then.... String objectMapper = null; try { objectMapper = new ObjectMapper().writeValueAsString(skillsMap); } catch (JsonProcessingException e) { e.printStackTrace(); } model.addAttribute("skillsMap", objectMapper);```
  2. This time When I attempt to bind this to my JavaScript variable, the object looks like this when I debug in my browser: -这次当我尝试将它绑定到我的 JavaScript 变量时,当我在浏览器中调试时,object 看起来像这样:-

var skillsMapJson = {&quot;Languages_OD&quot;:[{&quot;id&quot;:66,&quot;name&quot;:&quot;SQL&quot;},{&quot;id&quot;:67,&quot;name&quot;:&quot;PL/SQL&quot;}], etc, etc};

The JSON now looks valid, but all the quotes are escaped and it now throws a different exception: - JSON 现在看起来有效,但是所有引号都被转义了,它现在抛出了一个不同的异常:-

```Uncaught SyntaxError: Unexpected token &```

I feel that if the JSON string contained actual quotes instead of " the Map would successfully bind to my variable. I would appreciate any advice as to how to deal with this. Many thanks for reading.我觉得如果 JSON 字符串包含实际引号而不是“ Map 将成功绑定到我的变量。我将不胜感激有关如何处理此问题的任何建议。非常感谢您的阅读。

EDIT: Screenshot of error added below: -编辑:下面添加的错误截图:-

JavaScript 变量中的 JSON 编码问题

I did eventually get round this problem and so am offering a solution in case it helps anyone else.我最终确实解决了这个问题,因此我提供了一个解决方案,以防它对其他人有所帮助。 However, I feel that the solution is a bit 'hacky' and so would welcome any further answers that improve on this or offer a more elegant solution.但是,我觉得该解决方案有点“hacky”,因此欢迎任何进一步的答案来改进此问题或提供更优雅的解决方案。

The problem was in the way I was trying to retrieve my map from the Model and assign to a JavaScript variable.问题在于我试图从 Model 检索我的 map 并分配给 JavaScript 变量的方式。 Initially, I was trying this: -最初,我正在尝试这个: -

var skillsMapRawString = [[${skillsMapJson}]];

The trouble is that this way of referencing skillsMapJson forces JavaScript to treat it as an Object and it cannot deal with the encoding issue described in the original post when attempting to deserialize it into JSON.问题在于,这种引用技能MapJson 的方式强制 JavaScript 将其视为 Object 并且在尝试将其反序列化为 Z0ECD11C1AD7A287401D8ZD14 时,它无法处理原始帖子中描述的编码问题。 The above line therefore threw the exception "unexpected token &".因此,上面的行抛出了异常“unexpected token &”。

By adding single quotes around the object reference, JavaScript is forced to treat skillsMapJson as a String and not an object: -通过在 object 引用周围添加单引号,JavaScript 被迫将技能MapJson 视为字符串而不是 object:-

var skillsMapRawString = '[[${skillsMapJson}]]';

The above variable assignment now works successfully, but we still have the problem that it contains encoded quotes which prevent it being parsed to a JSON Object.上面的变量赋值现在可以成功运行,但我们仍然遇到它包含编码引号的问题,这会阻止它被解析为 JSON Object。 This is where it feels like a bit of a hack, because I got round this by doing a global replace on the String: -这是感觉有点像黑客的地方,因为我通过对字符串进行全局替换来解决这个问题:-

var skillsMapJSONString = skillsMapRawString.replace(/&quot;/g, "\"");

Having replaced the encoded sections that were causing problems before, the String can now be parsed as JSON: -替换了之前导致问题的编码部分后,现在可以将字符串解析为 JSON:-

var skillsMapParsed = JSON.parse(skillsMapJSONString);

And finally, I have my map of lists successfully assigned to a JavaScript variable: :)最后,我将列表的 map 成功分配给 JavaScript 变量::)

Symbols "&quot;"符号"&quot;" and similar are HTML escapes.和类似的是 HTML 转义。 So your info is HTML escaped.所以你的信息是 HTML 转义。 You can unescape it back by using class org.apache.commons.text.StringEscapeUtils from the library apache.commons/commons-text .您可以使用库apache.commons/commons 中的class org.apache.commons.text.StringEscapeUtils将其取消转义The info found at: How to unescape HTML character entities in Java?在以下位置找到的信息: 如何在 Java 中取消转义 HTML 字符实体?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM