2

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)
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
Vipul
  • 33
  • 1
  • 6

2 Answers2

1

I don't know the API but from the looks of it you need to escape your ' characters ...

From a quick google search i found this: http://www.programcreek.com/java-api-examples/org.json.simple.parser.JSONParser

The code in the link basically tells you to use \" instead of ' in your String and your JSONParser should understand it. Hope this helps.

mind_
  • 134
  • 2
  • 9
1

You can't use single quotes.

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.

Another option is to use escaped double quotes.

String expiryDateString = "{\"expire_on\":\"Aug 05, 2016\"}";  
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76