【问题标题】:Validating JSON using GSON in java在 Java 中使用 GSON 验证 JSON
【发布时间】: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;

}

【问题讨论】:

标签: java json gson


【解决方案1】:

现在它会将第二个引号视为 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...

【讨论】:

  • 实际上,在我的情况下,我没有将其存储在字符串中,而是使用 rest 客户端将 uri 发送到 rest 服务,并且我发送正文如下:{"hashkey":{"calculatedHMAC":" f7b5addd27a221b216068cddb9abf1f06b3c0e1c","secretkey":"12345"},"operation":"read","attributes":["name","id"],"otid":"12"} 然后存储在一个字符串中休息服务作为休息服务接收它作为字符串但是当我打印它时。打印相同: {"hashkey":{"calculatedHMAC":"f7b5addd27a221b216068cddb9abf1f06b3c0e1c","secretkey":"12345"},"operation":"read","attributes":["name","id"], "otid":"12"} 所以这里没有单引号。
  • 同样的事情也适用于双引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
相关资源
最近更新 更多