繁体   English   中英

在java中使用GSON验证JSON

[英]Validating JSON using GSON in java

我正在使用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;

}

现在它将第二个引用视为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字符串引用?

阅读更多...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM