Vipul Vipul - 4 months ago 15
JSON Question

JSON data in single quote

I have an expiry date in JSON formate and I want to get this expiry date in string variable so what should I do?
public class ExpiryDate {

public String getExpiryDate() throws ParseException, IOException{

String expiryDateString = "{'expire_on':'Aug 05, 2016'}";

JSONParser jsonParser = new JSONParser();

Object obj = jsonParser.parse(expiryDateString);

JSONObject jsonObject = (JSONObject) obj;

System.out.println(jsonObject);

return "";
}

}


I am passing this JSON data but at Object create line i got this exception

Unexpected character (') at position 1.
at org.json.simple.parser.Yylex.yylex(Unknown Source)
at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at onbording.ExpiryDate.getExpiryDate(ExpiryDate.java:25)
at onbording.Sendmail.handleRequest(Sendmail.java:57)
at example.sendmailTest.testsendemail(sendmailTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Answer

You can't use single qoutes.

You're probably using Java. I would suggest you to use JSONObject.

JSONObject jsonObject = new JSONObject();
jsonObject.put("expire_on", "Aug 05, 2016");
String expiryDateString = jsonObject.toString();

It's usually better practice to handle JSON like this, than creating JSON string manually.

Other option is to use escaped double qoutes.

String expiryDateString = "{\"expire_on\":\"Aug 05, 2016\"}";