Soy un poco nuevo en la actualización y no estoy seguro de cómo manejar una estructura JSON anidada como esta. si alguien puede ayudar a analizar este tipo de estructura. Realmente lo agradecería. He estado atrapado por días

{
"status": "ok",
"totalResults": 20,
"articles": [
{
"source": {
"id": null,
"name": "Bradenton.com"
},
"author": "By EILEEN NG  Associated Press",
"title": "Malaysia says search for missing plane to end in June",
"description": "An official says the search for Malaysia Airlines Flight 370 by a U.S. company will likely end in June, as families of passengers marked the fourth anniversary of the plane's disappearance with hope that the world's biggest aviation mystery will be solved.",
"url": "http://www.bradenton.com/news/business/article203286984.html",
"urlToImage": "http://www.mcclatchy-wires.com/incoming/ukogzw/picture203286949/alternates/LANDSCAPE_1140/Malaysia_Missing_Plane_57970.jpg",
"publishedAt": "2018-03-03T09:42:00Z"
}
]
}
1
Salman Khan 3 mar. 2018 a las 16:14

5 respuestas

La mejor respuesta

http://www.jsonschema2pojo.org/ para convertir su json a POJO y usarlo para la actualización 2.3

2
Sabid Habib 3 mar. 2018 a las 13:23

Bien, cuando trabaje con la actualización, sugiero usar la biblioteca Gson con ella, que analiza su json en un tipo de objeto que debería ha creado tan primero que debe crear un objeto que represente su objeto a partir de la respuesta que obtiene, por lo que será algo así en su caso

public class Article implements Serializable {
private String author;
private String title;
private String description;
private String url;
private String urlToImage;
private String publishedAt;
private Source source;

public Story() {

}

public Story(String author,
             String title,
             Source source,
             String description,
             String url,
             String urlToImage,
             String publishedAt) {

    this.author = author;
    this.title = title;
    this.source = source;
    this.url = url;
    this.urlToImage = urlToImage;
    this.publishedAt = publishedAt;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public double getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getUrlToImage() {
    return urlToImage;
}

public void setUrlToImage(String urlToImage) {
    this.urlToImage = urlToImage;
}

public String getPublishedAt() {
    return publishedAt;
}

public void setPublishedAt(String publishedAt) {
    this.publishedAt = publishedAt;
}

public Source getSource() {
    return source;
}

public void setSource(Source source) {
    this.source = source;
}
}

Y de manera similar, cree su otra clase, que es la clase Source que contiene su objeto Source

public class Source implements Serializable {
   private id id;
   private String name;

   public Source() {

   }

   public Source(int id,
         String name) {

       this.id = id;
       this.name = name;
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
 }

Ahora en su código de API de actualización podría hacer algo como esto

 @GET("YOUR_ENDPOINT/")
 Call<JsonObject> getArticles(... put your required fields here example ...@Query("token") String token);

Y en tu actividad haz algo como esto

List mArticleList = new ArrayList<>();
String mTotalResults = "";
UserApi service  =  ServiceGenerator.createService(UserApi.class);
Call<JsonObject> result = service.getArticles(token);

result.enqueue(new Callback<JsonObject>() {
     @Override
     public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
        if (response.code() == 200) {
           mArticleList = null;
           JsonArray data = response.body().getAsJsonObject("data").getAsJsonArray("articles");
           mArticleList = new Gson().fromJson(data.toString(), new TypeToken<List<Article>>(){}.getType());
           mTotalResults = response.body().getAsJsonObject("data").getAsString("totalResults");
//if you want it as an integer you could do something like 
           int totalResults = Integer.parseInt(mTotalResults);
           //... do what you want with your list
           //...
         }
    }
            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                //do what you have to do in case of error
            }
        });
    }

Espero que esto ayude

0
Ali Kaissi 3 mar. 2018 a las 14:38

Si no sabe cuántas clases necesita hacer, simplemente copie y pegue su json aquí haga clic aquí.

Esto lo ayudará y facilitará su trabajo.

1
Arjun 3 mar. 2018 a las 13:25

Crea algunos pojos:

class Source {
   String id;
   String name;
}

class Article{
   Source source;
   String author;
   String title;
   String description;
   String url;
   String urlToImage;
   String publishedAt;
}

class GetArticlesResponse{
   String status;
   int totalResults;
   List<Article> articles;
}

Y luego pase GetArticlesResponse a su llamada de modificación.

import retrofit2.Response;
import retrofit2.Call;
public interface YourInterface {
  @GET("your_end_point")
  Call<Response<GetArticlesResponse>> getArticles();
}

O si estás usando RX:

import retrofit2.Response;
import rx.Observable;

public interface YourInterface {
  @GET("your_end_point")
  Observable<Response<GetArticlesResponse>> getArticles();
}
1
Levi Moreira 3 mar. 2018 a las 13:27

MainClass.java

public class MainClass {

@SerializedName("status")
@Expose
private String status;
@SerializedName("totalResults")
@Expose
private Integer totalResults;
@SerializedName("articles")
@Expose
private List<Article> articles = null;

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public Integer getTotalResults() {
return totalResults;
}

public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults; 
}

public List<Article> getArticles() {
return articles;
}

public void setArticles(List<Article> articles) {
this.articles = articles;
}

}

Article.java

public class Article {

 @SerializedName("source")
 @Expose
 private Source source;
 @SerializedName("author")
 @Expose
 private String author;
 @SerializedName("title")
 @Expose
 private String title;
 @SerializedName("description")
 @Expose
 private String description;
 @SerializedName("url")
 @Expose
 private String url;
 @SerializedName("urlToImage")
 @Expose
 private String urlToImage;
 @SerializedName("publishedAt")
 @Expose
 private String publishedAt;

 public Source getSource() {
 return source;
 }

 public void setSource(Source source) {
 this.source = source;
 }

 public String getAuthor() {
 return author;
 }

 public void setAuthor(String author) {
 this.author = author;
 }

 public String getTitle() {
 return title;
 }

 public void setTitle(String title) {
 this.title = title;
 }

 public String getDescription() {
 return description;
 }

 public void setDescription(String description) {
 this.description = description;
 }

 public String getUrl() {
 return url;
 }

 public void setUrl(String url) {
 this.url = url;
 }

 public String getUrlToImage() {
 return urlToImage;
 }

 public void setUrlToImage(String urlToImage) {
 this.urlToImage = urlToImage;
 }

 public String getPublishedAt() {
 return publishedAt;
 }

 public void setPublishedAt(String publishedAt) {
 this.publishedAt = publishedAt;
 }

 }

Source.java

public class Source {

@SerializedName("id")
@Expose
private Object id;
@SerializedName("name")
@Expose
private String name;

public Object getId() {
return id;
}

public void setId(Object id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Interfaz de actualización

public interface YourInterface {
@GET("whatever api u are using")
Call<MainClass> getData(@Query("whatever key") String/int(whatever name)) //or leave blank
}
0
Arpit todewale 3 mar. 2018 a las 14:31