Convert a String Arraylist to a Json

Asked

Viewed 987 times

4

I need to convert one ArrayList of String on a JSON.

I have a method in which I get a list of apps installed on the mobile device. This method returns me the data in a String Arraylist.

I was able to generate a JSON using JSONArray but I couldn’t insert a tag inside Json, below is JSON using JSONArray.

Json: ["com.br.package1", "com.br.package2", "com.br.package3"]

I need Json to look like this:

[{"name": "com.br.package1"},{"name": "com.br.package2"}, {"name":"com.br.package3"}]

Below is an excerpt of the code:

//Cria e inicializa ArrayList que contem os packages instalados no Aparelho
ArrayList<String> mPackages = new ArrayList<String>();

//Grava no ArrayList o retorno do método
mPackages = Util.buscaAppsInstalados(getBaseContext());

JSONArray jsonArray = new JSONArray(mPackages);
  • This "name" is fixed?

  • Hello Pablo yes is fixed

1 answer

6


You’ll have to build a Jsonobject for each item of mPackages and add it to the Jsonarray:

//Cria e inicializa ArrayList que contem os packages instalados no Aparelho
ArrayList<String> mPackages = new ArrayList<String>();

//Grava no ArrayList o retorno do método
mPackages = Util.buscaAppsInstalados(getBaseContext());

//Cria um JSONArray
JSONArray jsonArray = new JSONArray();

//Percorre mPackages
for(String name : mPackages){

    //Cria um JSONObject por cada item
    JSONObject jsonObject = new JSONObject();

    try {
        //Constroi o JSONObject
        jsonObject.put("name", name);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //Adiciona-o ao JSONArray
    jsonArray.put(jsonObject);
}
  • Thank you, it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.