简体   繁体   中英

How to convert Invalid JSON String to JSONObject in Java?

I have a string response like below which is a invalid json as it contains "obj13=" .I want to convert it to a JSONObject(JAVA) and use it.Is there any good way to convert it to JSONObject without using String split operation.

obj13={
  players: [
    {
      name: "rocky",
      place: "brazil",
      age: "21",
    },
    {
      name: "andy",
      place: "New Zealand",
      age: "23",
    }
  ]
}

This is, of course, JavaScript, not JSON. If you can, I would go back to the service provider and ask for a JSON response.

If the format of the string is consistent, you could just use:

json=json.substring(json.indexof('=')+1);  

and then parse the result. Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas ( mine does , but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).

If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM