spen123
spen123

Reputation: 3524

Make JSONArray from string Android - Java

I have a string that looks like this

"{"resturant_name": "Chipotle", "street": "431 Liberty St"},
{"resturant_name": "MCDoNalds", "street": "1 Main St"},
{"resturant_name": "Wednys", "street": "5 Main St"}"

And I want to turn into a JSONArray so I can loop though and get the name?

But when I do

JSONArray jsonArray = new JSONArray(string);

I get an error

type of org.json.JSONObject cannot be converted to JSONArray,

How can I make this a JSONArray so I can loop though it?

Thanks

Upvotes: 2

Views: 56

Answers (1)

Chris
Chris

Reputation: 1220

That's because your string is not JSON. It's close, but not quite. JSON standards dictate that the structure should either be an Object or an Array. To create an Array, it must begin with "[" and end with "]". So, your string should look like:

[{"resturant_name": "Chipotle", "street": "431 Liberty St"},
{"resturant_name": "MCDoNalds", "street": "1 Main St"},
{"resturant_name": "Wednys", "street": "5 Main St"}]

Upvotes: 4

Related Questions