-1

I'am getting jsonobject as [{"id":"[66]"}] how can i convert to jsonarray?

Here is my code:
 public Object[] showCampaigns(@RequestParam("selectedAccId") String selectedAccId, HttpSession session, Model model) {
        Object[] responseBody = new Object[1];
        List<Long> accountIds=new ArrayList<>();

        try {
            JSONArray clientjson = new JSONArray(selectedAccId);

            for (int i = 0; i < clientjson.length(); ++i) {
                JSONObject rec = clientjson.getJSONObject(i);
                long id = Long.parseLong(rec.getString("id"));
                accountIds.add(id);
            }
}

Error I'am gettinbg is: Long.parseLong(rec.getString("id")) = >Exception occurred in target VM: For input string: "[66]"<

eshwar chettri
  • 310
  • 4
  • 16

2 Answers2

0

The value for the key id is, as a string, "[66]", which is not actually parsable as a long.

The problem is not necessarily with your code, but with the server from which this response comes, this is where is should be corrected.

If that is not possible:

You need to fetch this as a string, and parse it your own; here is a regex to strip any non digit.

...
// strip any non digit
String number = rec.getString("id").replaceAll("\\D+","");

// parse number only string
long id = Long.parseLong(number);

source of regex

Community
  • 1
  • 1
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
0

you are trying to parse the String having '[66]' to Long.

You can only transform string which are having only digits to Long

 long id = Long.parseLong(rec.getString("id"));

visualize this code as

 long id = Long.parseLong("[66]");

Beacuse of this you are getting the issue.

Try to use something like this to remove all punctuation from string including opening and closing brackets.

String stringId= rec.getString("id").replaceAll("\\p{P}","");
 long id = Long.parseLong(stringId);
Dhiraj
  • 1,430
  • 11
  • 21