在java中使用GSON验证JSON

时间:2014-07-31 14:59:50

标签: 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");
}

它做得很好但是当我删除下面的引号时,我已经从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;

}

1 个答案:

答案 0 :(得分:3)

现在它会将第二个引用视为hashkey的一部分。看看下面从对象返回的json字符串。

我在jsonlint

测试了它
{
  "hashkey\u0027": {
    "calculatedHMAC": "f7b5addd27a221b216068cddb9abf1f06b3c0e1c",
    "secretkey": "12345"
  },
  "operation\u0027": "read",
  "attributes": [
    "name",
    "id"
  ],
  "otid": "12"
}

示例代码:

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");
}
  

JSON字符串是否需要引用密钥?

Read more...