开发者

JsonParseException while parsing from String to Map

开发者 https://www.devze.com 2023-01-29 12:03 出处:网络
I have done Map object to string object conversion like this public String getJsonString(Map<String, Map<String,List<CalculateContentCount>>> countMap) {

I have done Map object to string object conversion like this

    public String getJsonString(Map<String, Map<String,List<CalculateContentCount>>> countMap) {
    Gson gson = new Gson();
    String jsonString = gson.toJson(countMap);
    return jsonString;
}

In ftl I have set the returned String object into request and pased it into the JSP file

   <#assign countMap = json>
   <form action="/alfresco/jsp/kpub/reports/exportContentCountList.jsp" method="get">

<input type="hidden" name="countMap" id="countMap" value="${countMap}">
<input type="submit" value="ExportFiletoCSV"/>
   </form>

In exportContentCountList, I tried to parse the string object back to Map object,

String jsonString = request.getParameter("countMap");
System.out.println("jsonString : "+jsonString);
Gson gson = new Gson();
Map<String,Map<String,List<CalculateContentCount>>> countMap = null;
Type type = null;
if(jsonString != null && !"".equals(jsonString)) {
    type = new TypeToken<Map<String,Map<String,List<CalculateKpubContentCount>>>>(){}.getType();
    countMap = gson.fromJson(jsonString,type);
}

While executing, following exception occurs. Here's the exceptiom

com.google.gson.JsonParseException: Failed parsing JSON source:        
caused by:
com.google.gson.ParseException: Encountered "<EOF>" at line 1, column 1. 
Was expecting one of: 
<IDENTIFIER_SANS_EXPONENT> ... 
<IDENTIFIER_STARTS_WITH_EXPONENT> ... 
开发者_JS百科<SINGLE_QUOTE_LITERAL> ... 
<DOUBLE_QUOTE_LITERAL> ... 
"}" ... 

What may be the problem?


Check the generated HTML output. Rightclick page in webbrowser and choose View Source. Does it look right? Also the double quotes? Gson output JSON strings with double quotes. In other words, the generated HTML is syntactically invalid.

Use JSTL fn:escapeXml() to escape HTML special characters like <, >, ", ' so that they won't malform the HTML syntax.

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<input type="hidden" name="countMap" id="countMap" value="${fn:escapeXml(countMap)}">

This way the entire string will be passed back instead of only a part until the first quote (which caused Gson to detect an EOF (End Of File, or better to be interpreted as End Of String).


Update:

If you can't use JSTL, you have to use String#replace() to escape HTML entities manually. E.g.

return jsonString.replace("\"", "&quot;");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号