尝试使用JSON格式将请求数据从JavaScript转换为Java。 JavaScript中的请求正文如下所示:
{
"id": "3",
"name": "Chicken pasta",
"description": "Lets make chicken pasta",
"category": "Unassigned",
"favorite": true,
"prepTime": "",
"cookTime": "",
"ingredients": [
{}
],
"steps": [],
"user": {
"id": "2",
"username": "user2"
}
}
但是在服务器端(在我的Java控制器中)它是:
%7B%0A%09%22id%22%3A+%223%22%2C%0A%09%22name%22%3A+%22Chicken+pasta%22%2C%0A%09%22description%22%3A+%22Lets+make+chicken+pasta%22%2C%0A%09%22category%22%3A+%22Unassigned%22%2C%0A%09%22favorite%22%3A+true%2C%0A%09%22prepTime%22%3A+%22%22%2C%0A%09%22cookTime%22%3A+%22%22%2C%0A%09%22ingredients%22%3A+%5B%0A%09%09%7B%7D%0A%09%5D%2C%0A%09%22steps%22%3A+%5B%5D%2C%0A%09%22user%22%3A+%7B%0A%09%09%22id%22%3A+%222%22%2C%0A%09%09%22username%22%3A+%22user2%22%0A%09%7D%0A%7D=
所以我得到了JSON解析异常。 怎么编码呢?
答案 0 :(得分:1)
您在服务器上收到的字符串是URL编码的。您需要对URL进行URL解码,然后才能将其解析为JSON。有关java中的URL解码,请参阅this SO question。
答案 1 :(得分:1)
是的,托马斯,你说对了,我已经发现了。但是没有使用过URLDecoder.decode,只写了我自己的几行代码:)
public static String toDecimal (String hexStr) {
char[] hex = hexStr.toCharArray();
char current;
String result = "";
for (int i=0;i<hex.length;i++) {
if (hex[i] == '%') {
current = (char) ((toDecimal(hex[i+1]) * 16) + toDecimal(hex[i+2]));
i+=2;
} else {
if (hex[i] == '+') {
current = ' ';
} else {
current = hex[i];
}
}
result += current;
}
while (!(result.endsWith("}") || result.endsWith("]"))) {
result = result.substring(0, result.length()-1);
}
return result;
}
private static int toDecimal (char hex) {
switch (hex) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': return 10;
case 'B': return 11;
case 'C': return 12;
case 'D': return 13;
case 'E': return 14;
case 'F': return 15;
}
return -1;
}
与前面提到的URLDecoder.decode方法相同的结果,但是我的函数也从末尾删除所有字符而没有找到Json('}'或']'的结尾),我不知道为什么,但我得到了字符串来自JS以'='符号结尾。