javajsonstringgetstring

How to escape special characters from JSON when assign it to Java String?


I'm trying to assign a value from JSON to Java String, but the JSON value is including some special characters \. When I was trying to assign it to the string it gave an error.

This is the JSON value:

"ValueDate":"\/Date(1440959400000+0530)\/"

This is how I trying to use it:

HistoryVO.setValueDate(DataUtil.getDateForUnixDate(historyJson.getString("ValueDate")));

or

enter image description here


Solution

  • If you have specific character, ( and ), use substring method to get the value.

        String value = "\\/Date(1440959400000+0530)\\/";
        int start = value.indexOf("(");
        int last = value.lastIndexOf("0");
        value = value.substring(start + 1, last + 1);
        System.out.println(value); <--- 1440959400000+0530
    
        DataUtil.getDateForUnixDate(value);
    

    I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.

    Update

    To remove / character use replace method.

        String value = "/Date(1440959400000+0530)/";
        value = value.replace("/", "");
        System.out.println(value);
    

    output

    Date(1440959400000+0530)