【发布时间】:2014-07-31 14:59:50
【问题描述】:
我正在使用 GSON 来验证 JSON 格式的字符串:
String json="{'hashkey':{'calculatedHMAC':'f7b5addd27a221b216068cddb9abf1f06b3c0e1c','secretkey':'12345'},operation':'read','attributes':['name','id'],'otid':'12'}";
Gson gson=new Gson();
Response resp = new Response();
RequestParameters para = null;
try{
para = gson.fromJson(json, RequestParameters.class);
}catch(Exception e){
System.out.println("invalid json format");
}
它做得很好,但是当我删除下面这样的引号时,我已经从 hashkey 中删除了:
"{hashkey':{'calculatedHMAC':'f7b5addd27a221b216068cddb9abf1f06b3c0e1c','secretkey':'12345'},operation':'read','attributes':['name','id'],'otid':'12'}"
它仍在将其验证为正确的 JSON 格式,并且不会抛出任何异常,也不会进入 catch 正文。有什么理由这样做吗?我将如何解决这个问题?
RequestParameters 类:
public class RequestParameters {
HashKey hashkey;
String operation;
int count;
int otid;
String[] attributes;
}
【问题讨论】:
-
请同时发布您的 RequestParameters 类,以便我们查看它映射到哪些字段。
-
另请参阅How to check if JSON is valid in Java using GSON,了解工作 gson 严格解析解决方法。