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;
}
                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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With