Cómo analizar JSON Array con Gson

Quiero analizar las matrices JSON y el uso de gson. En primer lugar, puedo registrar la salida de JSON, servidor es responsing al cliente claramente.

Aquí está mi salida de JSON:

[ { id : '1', title: 'sample title', .... }, { id : '2', title: 'sample title', .... }, ... ] 

He intentado esta estructura para el análisis. Una clase, que depende de una array única y ArrayList para todos JSONArray.

  public class PostEntity { private ArrayList<Post> postList = new ArrayList<Post>(); public List<Post> getPostList() { return postList; } public void setPostList(List<Post> postList) { this.postList = (ArrayList<Post>)postList; } } 

Clase de post:

  public class Post { private String id; private String title; /* getters & setters */ } 

Cuando intento utilizar gson ningún error, ninguna advertencia y ningún registro:

  GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); PostEntity postEnt; JSONObject jsonObj = new JSONObject(jsonOutput); postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class); Log.d("postLog", postEnt.getPostList().get(0).getId()); 

¿Qué pasa? ¿Cómo puedo solucionarlo?

Puede analizar la matriz JSON directamente, no es necesario que envuelva su clase Post con PostEntity una vez más y no necesite nuevo JSONObject (). ToString ():

 Gson gson = new Gson(); String jsonOutput = "Your JSON String"; Type listType = new TypeToken<List<Post>>(){}.getType(); List<Post> posts = (List<Post>) gson.fromJson(jsonOutput, listType); 

Espero que ayude.

Buscaba una forma de analizar las matrices de objetos de una manera más genérica; Aquí está mi contribución:

CollectionDeserializer.java :

 import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; public class CollectionDeserializer implements JsonDeserializer<Collection<?>> { @Override public Collection<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0]; return parseAsArrayList(json, realType); } /** * @param serializedData * @param type * @return */ @SuppressWarnings("unchecked") public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) { ArrayList<T> newArray = new ArrayList<T>(); Gson gson = new Gson(); JsonArray array= json.getAsJsonArray(); Iterator<JsonElement> iterator = array.iterator(); while(iterator.hasNext()){ JsonElement json2 = (JsonElement)iterator.next(); T object = (T) gson.fromJson(json2, (Class<?>)type); newArray.add(object); } return newArray; } } 

JSONParsingTest.java :

 public class JSONParsingTest { List<World> worlds; @Test public void grantThatDeserializerWorksAndParseObjectArrays(){ String worldAsString = "{\"worlds\": [" + "{\"name\":\"name1\",\"id\":1}," + "{\"name\":\"name2\",\"id\":2}," + "{\"name\":\"name3\",\"id\":3}" + "]}"; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Collection.class, new CollectionDeserializer()); Gson gson = builder.create(); Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class); assertNotNull(decoded); assertTrue(JSONParsingTest.class.isInstance(decoded)); JSONParsingTest decodedObject = (JSONParsingTest)decoded; assertEquals(3, decodedObject.worlds.size()); assertEquals((Long)2L, decodedObject.worlds.get(1).getId()); } } 

World.java :

 public class World { private String name; private Long id; public void setName(String name) { this.name = name; } public String getName() { return name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } 
 Type listType = new TypeToken<List<Post>>() {}.getType(); List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType); 
  • Cómo mantener múltiples google-service.json en Android Studio
  • Cómo enviar datos JSON ARRAY al servidor en Android
  • Cómo crear datos de formato JSON en android?
  • Android ¿Cómo puedo leer el archivo json (archivo de texto) de la tarjeta SD y mostrar los datos en textview
  • Poner byte en JSON en android
  • Cómo obtener actualizaciones en vivo a través de JSON a listview
  • Necesito descargar varias imágenes al directorio para poder acceder al contenido sin conexión
  • Tiempo de viaje entre dos ubicaciones en Google Map Android API V2
  • Android conexión a json / xml api
  • Cómo generar JsonStringer para este formato de datos Json?
  • Android - Error en la conexión http java.net.UnknownHostException:
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.