MadukaJ
MadukaJ

Reputation: 761

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

Upvotes: 0

Views: 1941

Answers (4)

Zaw Than oo
Zaw Than oo

Reputation: 9935

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)

Upvotes: 1

MadukaJ
MadukaJ

Reputation: 761

i found the answer for my own question.

historyJson.getString("ValueDate");

this return the String like /Date(1440959400000+0530)/

now i can split it. thank you all for the help.

regards, macdaddy

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

Given that

I want ... to get [the] Date(1440959400000+0530) part,

I would use

String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
  int pos2 = value.indexOf(")", pos1);
  if (pos2 > pos1) {
    value = value.substring(pos1, pos2 + 1);
    System.out.println(value);
  }
}

Output is

Date(1440959400000+0530)

Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.

Upvotes: 2

Coder
Coder

Reputation: 3262

Mac,

As you asked for something like

String ValueDate = "\/Date(1440959400000+0530)\/";

The above one is not possible in java string, As it shows as invalid escape sequence, So replace the slash '\' as double slash '\' as below,

String ValueDate = "\\/Date(1440959400000+0530)\\/";

If am not clear of our question, pls describe it clearly

Regards, Hari

Upvotes: 1

Related Questions