在java中使用GSON验证JSON

Mr3*_*037 5 java json gson

我正在使用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");
}
Run Code Online (Sandbox Code Playgroud)

它做得很好但是当我删除下面的引号时,我已经从hashkey中删除了:

"{hashkey':{'calculatedHMAC':'f7b5addd27a221b216068cddb9abf1f06b3c0e1c','secretkey':'12345'},operation':'read','attributes':['name','id'],'otid':'12'}"
Run Code Online (Sandbox Code Playgroud)

它仍然将它验证为正确的JSON格式,并且不会抛出任何异常而不会进入catch体.这样做的原因是什么?我该如何解决这个问题?

RequestParameters类:

public class RequestParameters {
    HashKey hashkey;
    String operation;
    int count;
    int otid;
    String[] attributes;

}
Run Code Online (Sandbox Code Playgroud)

Bra*_*raj 3

现在它将把第二个引号视为哈希键的一部分。看一下下面从对象返回的 json 字符串。

我在jsonlint上测试了它

{
  "hashkey\u0027": {
    "calculatedHMAC": "f7b5addd27a221b216068cddb9abf1f06b3c0e1c",
    "secretkey": "12345"
  },
  "operation\u0027": "read",
  "attributes": [
    "name",
    "id"
  ],
  "otid": "12"
}
Run Code Online (Sandbox Code Playgroud)

示例代码:

String json = "{hashkey':{'calculatedHMAC':'f7b5addd27a221b216068cddb9abf1f06b3c0e1c','secretkey':'12345'},operation':'read','attributes':['name','id'],'otid':'12'}";
Gson gson = new Gson();
try {
    Object o = gson.fromJson(json, Object.class);
    System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(o));
} catch (Exception e) {
    System.out.println("invalid json format");
}
Run Code Online (Sandbox Code Playgroud)

JSON 字符串与键之间是否需要引用?

阅读更多...