Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating JSON using GSON in java

Tags:

java

json

gson

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

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?

RequestParameters class:

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

}
like image 279
Mr37037 Avatar asked Oct 21 '22 04:10

Mr37037


1 Answers

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

I tested it at 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?

Read more...

like image 82
Braj Avatar answered Oct 23 '22 09:10

Braj