Convert a String ArrayList to a Json

4

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

I have a method where I get a list of apps installed on the mobile device. This method returns the data in a String ArrayList.

I was able to generate a JSON using JSONArray but I was unable to insert a tag inside Json, it follows 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"}]

Here is an excerpt from 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);
    
asked by anonymous 26.01.2016 / 21:22

1 answer

6

You must first construct a JSONObject for each item of mPackages and add it to 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);
}
    
26.01.2016 / 23:04