Cómo convertir HashMap a json Array en android?

Quiero convertir HashMap a json array mi código es como sigue:

Map<String, String> map = new HashMap<String, String>(); map.put("first", "First Value"); map.put("second", "Second Value"); 

He intentado esto pero no funcionó

 JSONArray mJSONArray = new JSONArray(Arrays.asList(map)); 

Prueba esto,

 public JSONObject (Map copyFrom) 

Crea un nuevo objeto JSONO copiando todas las asignaciones de nombre / valor del mapa dado.

Parámetros copyFrom un mapa cuyas claves son del tipo String y cuyos valores son de tipos soportados.

Lanza NullPointerException si alguna de las claves del mapa es null.

Uso básico:

 JSONObject obj=new JSONObject(yourmap); 

Obtener la matriz json del objeto JSONObject

Editar:

 JSONArray array=new JSONArray(obj.toString()); 

Editar: (Si se encuentra Excepción, a continuación, puede cambiar como mención en el comentario por @ krb686)

 JSONArray array=new JSONArray("["+obj.toString()+"]"); 

Desde androiad API Lvl 19, usted puede hacer simplemente new JSONObject(new HashMap()) . Pero en los lvls de API más antiguos obtienes un resultado feo (aplique simple toString a cada valor no primitivo).

Recopilé métodos de JSONObject y JSONArray para simplificar y resultado bonito. Puedes usar mi clase de solución:

 package you.package.name; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; public class JsonUtils { public static JSONObject mapToJson(Map<?, ?> data) { JSONObject object = new JSONObject(); for (Map.Entry<?, ?> entry : data.entrySet()) { /* * Deviate from the original by checking that keys are non-null and * of the proper type. (We still defer validating the values). */ String key = (String) entry.getKey(); if (key == null) { throw new NullPointerException("key == null"); } try { object.put(key, wrap(entry.getValue())); } catch (JSONException e) { e.printStackTrace(); } } return object; } public static JSONArray collectionToJson(Collection data) { JSONArray jsonArray = new JSONArray(); if (data != null) { for (Object aData : data) { jsonArray.put(wrap(aData)); } } return jsonArray; } public static JSONArray arrayToJson(Object data) throws JSONException { if (!data.getClass().isArray()) { throw new JSONException("Not a primitive data: " + data.getClass()); } final int length = Array.getLength(data); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < length; ++i) { jsonArray.put(wrap(Array.get(data, i))); } return jsonArray; } private static Object wrap(Object o) { if (o == null) { return null; } if (o instanceof JSONArray || o instanceof JSONObject) { return o; } try { if (o instanceof Collection) { return collectionToJson((Collection) o); } else if (o.getClass().isArray()) { return arrayToJson(o); } if (o instanceof Map) { return mapToJson((Map) o); } if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof String) { return o; } if (o.getClass().getPackage().getName().startsWith("java.")) { return o.toString(); } } catch (Exception ignored) { } return null; } } 

Entonces, si aplica el método mapToJson () a su Mapa, puede obtener resultados como este:

 { "int": 1, "Integer": 2, "String": "a", "int[]": [1,2,3], "Integer[]": [4, 5, 6], "String[]": ["a","b","c"], "Collection": [1,2,"a"], "Map": { "b": "B", "c": "C", "a": "A" } } 

Un mapa consta de pares clave / valor, es decir, dos objetos para cada entrada, mientras que una lista sólo tiene un único objeto para cada entrada. Lo que puede hacer es extraer todos los Map.Entry <K, V> y luego ponerlos en la matriz:

 Set<Map.Entry<String, String> entries = map.entrySet(); JSONArray mJSONArray = new JSONArray(entries); 

Alternativamente, a veces es útil extraer las claves o los valores de una colección:

 Set<String> keys = map.keySet(); JSONArray mJSONArray = new JSONArray(keys); 

o

 List<String> values = map.values(); JSONArray mJSONArray = new JSONArray(values); 

Nota: Si elige utilizar las teclas como entradas, el orden no está garantizado (el método keySet() devuelve un Set ). Esto se debe a que la interfaz de Map no especifica ningún orden (a menos que el Map pase a ser un SortedMap ).

Puedes usar

JSONArray jarray = JSONArray.fromObject(map );

Este es el método más simple.

Solo usa

 JSONArray jarray = new JSONArray(hashmapobject.toString); 
  • Retrofit: Se esperaba BEGIN_OBJECT pero era BEGIN_ARRAY
  • Lazy descargar imágenes en gridView
  • Diseño como la aplicación HotStar
  • Parse Dynamic Key Json String utilizando Retrofit
  • Android - La llamada requiere el nivel 9 de API (el min actual es 8): android.os.StrictMode # setThreadPolicy
  • Lectura de JSON con Retrofit
  • Aparece la tecla "nameValuePairs" extraña cuando se utiliza Gson
  • Creación de JSONObject de cadena en JAVA (org.json)
  • Nullpointerexception al intentar obtener json array o json object de json string
  • JSONException: El valor del tipo java.lang.String no se puede convertir en JSONObject
  • Acceder a un objeto JSON dentro de otro objeto JSON
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.