在 Java 中使用 GSON 验证 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25062298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:15:32  来源:igfitidea点击:

Validating JSON using GSON in java

javajsongson

提问by Mr37037

I'm using GSON to validate a string which is in JSON format:

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

Its doing good but when I remove the quotes like below, I have removed from hashkey:

它做得很好,但是当我删除如下引号时,我已从哈希键中删除:

"{hashkey':{'calculatedHMAC':'f7b5addd27a221b216068cddb9abf1f06b3c0e1c','secretkey':'12345'},operation':'read','attributes':['name','id'],'otid':'12'}"

It's still validating it as a proper JSONformat and not throwing any exception and not going in catch body. Any reason why it is doing so? How would I solve this?

它仍然将其验证为正确的 JSON 格式,并且不会抛出任何异常并且不会进入 catch 主体。有什么理由这样做吗?我将如何解决这个问题?

RequestParameters class:

请求参数类:

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

}

回答by Braj

Now it will treat second quote as part of hashkey. Have a look at below json string that is get back from the object.

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

I tested it at jsonlint

我在jsonlint 上测试过

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

sample code:

示例代码:

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

Is there quote needed around JSON string against keys?

JSON 字符串周围是否需要针对键的引号?

Read more...

阅读更多...