0

I have a variable which is a string of JSON, this JSON is an array of objects:

String actions = "[{'title': 'BBC', 'url': 'https://www.bbc.co.uk'}, {'title': 'GOOGLE', 'url': 'https://www.google.com'}]"

I need to convert this into some thing that I can use within my android app, so an array or object that I can iterate over. How would I go about this?

Kaushik
  • 6,150
  • 5
  • 39
  • 54
ChrisBratherton
  • 1,540
  • 6
  • 26
  • 63

3 Answers3

0

You should use org.json.JSONArray for that.

String actions = "[{'title': 'BBC', 'url': 'https://www.bbc.co.uk'}, {'title': 'GOOGLE', 'url': 'https://www.google.com'}]" 

JSONArray actionArray = new JSONArray(actions)
for(int x = 0; x < actionArray.length; x++ ){
    JSONAobject obj = actionArray.getJSONObject(x);
    String title = obj.optString("title");
    //Other code
}
michaelitoh
  • 2,317
  • 14
  • 26
0

Using Gson

String actions = "[{'title': 'BBC', 'url': 'https://www.bbc.co.uk'}, {'title': 'GOOGLE', 'url': 'https://www.google.com'}]";

List list = new Gson().fromJson(actions, List.class);

If your JSON has known structure you can map it to class, for example:

class Website {
        String title;
        String url;
}


Type type = new TypeToken<List<Website>>() {}.getType();
List<Website> list = new Gson().fromJson(actions, type);
Bartek
  • 2,109
  • 6
  • 29
  • 40
-1

In java, you can use json library for this purpose: https://mvnrepository.com/artifact/org.json/json

G.G.
  • 592
  • 5
  • 16