How to convert JSONArray to List?

I’m trying to create an extension based on an API, I’ve tried in several ways, but I’m not able to get the information that is inside each tag “name”.

I know you have all the code, but I’m at work so I don’t remember the whole code, just this one, at the moment.

String genres = "";
JSONArray jsonArray = json.getJSONArray("genres");
genres = String.valueOf(jsonArray);

Retorna :
“genres”:[{“id”:878,“name”:“Ficção científica”},{“id”:28,“name”:“Ação”},{“id”:12,“name”:“Aventura”}

I want it to return only the information that is inside the “name”

Ficção científica
Ação
Aventura

This is only rough code. If you need those names in list then

public YailList Names(String arrayString) throws JSONException {
  JSONArray jsonArray = new JSONArray(arrayString);
  ArrayList < String > arr = new ArrayList < String > ();
  for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject eachObject = jsonArray.getJSONObject(i);
    arr.add(eachObject.getString("name"));
  }
  return YailList.makeList(arr);
}

If you need in format with each name in a new line as string,

public String Names(String arrayString) throws JSONException {
  JSONArray jsonArray = new JSONArray(arrayString);
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < jsonArray.length(); i++) {
    sb.append(jsonArray.getJSONobject(i).getString("name")).append("\n");
  }
  return sb.toString();
}
1 Like

But what would it look like inside a “public void” ? :thinking:

I tried this way:

ArrayList<String> genres = new ArrayList<String>();
try {
    JSONArray jsonArray = json.getJSONArray("genres");
     for(int i = 0; i <jsonArray.length(); i++){
     genres.add(jsonArray.getJSONObject(i).getString("name"));

And this was the return.
[Ficção científica, Ação, Aventura]

Show whole code in the method .

How can a public void method have a return?

1 Like

I had to change a few things, but the base is this.

@SimpleFunction(description = "Website source-code")
    public void Movie(final int id, String language) {
        AsynchUtil.runAsynchronously(new Runnable() { 
            @Override
            public void run() {
                try {
                    BufferedReader readStream = new BufferedReader(
                            new InputStreamReader(
                                    (new URL("site")).openStream()));
                    final String data = readStream.readLine();
                    activity.runOnUiThread(new Runnable() { // Sempre acione eventos no thread da IU
                        String jsonResponse = data;

                        public void run() {
                            JSONObject json = null;
                            try {
                                json = new JSONObject(jsonResponse);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                          ArrayList<String> genres = new ArrayList<String>();
                            try {
                                JSONArray jsonArray = json.getJSONArray("genres");
                                for(int i = 0; i <jsonArray.length(); i++){
                                    genres.add(jsonArray.getJSONObject(i).getString("name"));

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

I’ve written this code from my phone and formatted using Java formatter. Hope it helps.

@SimpleEvent
public void GotNames(YailList names) {
  EventDispatcher.dispatchEvent(this, "GotNames", names);
}
@SimpleEvent
public void OnError(String error) {
  EventDispatcher.dispatchEvent(this, "OnError", error);
}
@SimpleFunction
public void Movie() {
  HttpURLConnection http = null;
  InputStream inputStream = null;
  (new Thread(new Runnable() {
   @override
    public void run() {
      try {
        URL url = new URL("siteUrl");
        http = (HttpURLConnection) url.openConnection();
        int responseCode = http.getResponseCode();
        if (responseCode / 2 == 0) {
          inputStream = http.getInputStream();
          String res = convertStreamToString(inputStream);
          if (res != null) {
            activity.runOnUiThread(new Runnable() {
             @Override
              public void run() {
                JSONObject jsonObject = new JSONObject(res);
                JSONArray jsonArray = jsonObject.getJSONArray("genres");
                ArrayList < String > arr = new ArrayList < String > ();
                for (int i = 0; i < jsonArray.length(); i++) {
                  JSONObject eachObject = jsonArray.getJSONObject(i);
                  arr.add(eachObject.getString("name"));
                }
                GotNames(YailList.makeList(arr));
              }
            });
          }
        }
      } catch(Exception e) {
        OnError(e.getMessage());
      } finally {
        if (http != null) {
          http.disconnect();
        }
        if (inputStream != null) {
          try {
            inputStream.close();
          } catch(IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  })).start();
}
private String convertStreamToString(InputStream is) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  try {
    int len;
    while ((len = is.read(buffer)) != -1) {
      baos.write(buffer, 0, len);
    }
    return baos.toString();

  } catch(IOException e) {
    e.printStackTrace();
  } finally {
    if (is != null) {
      try {
        is.close();
      } catch(IOException e) {
        e.printStackTrace();
      }
    }
    try {
      baos.close();
    } catch(IOException e) {
      e.printStackTrace();
    }
  }
  return null;
}
3 Likes

To convert an array to list:

ArrayList<> list = new ArrayList<>(Arrays.asList(array));
4 Likes

I think, he means JSONArray to YailList :sweat_smile:

1 Like