Java 改造2.3.0如何处理嵌套json?

Java 改造2.3.0如何处理嵌套json?,java,android,retrofit,Java,Android,Retrofit,我是个新手,不知道如何处理这样的嵌套json结构。如果有人能帮助解析这种类型的结构。我真的很感激。我被困了好几天了 { "status": "ok", "totalResults": 20, "articles": [ { "source": { "id": null, "name": "Bradenton.com" }, "author": "By EILEEN NG Associated Press", "title": "Malaysia says search for missing

我是个新手,不知道如何处理这样的嵌套json结构。如果有人能帮助解析这种类型的结构。我真的很感激。我被困了好几天了

{
"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"
}
]
}
创建一些POJO:

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;
}
类源代码{
字符串id;
字符串名;
}
班级文章{
来源;
字符串作者;
字符串标题;
字符串描述;
字符串url;
字符串urlToImage;
字符串数据;
}
类GetArticlesResponse{
字符串状态;
综合结果;
列出文章;
}
然后将GetArticles Response传递给您的改装呼叫

import retrofit2.Response;
import retrofit2.Call;
public interface YourInterface {
  @GET("your_end_point")
  Call<Response<GetArticlesResponse>> getArticles();
}
2.响应;
2.电话;;
公共接口YourInterface{
@获取(“你的终点”)
调用getArticles();
}
或者如果您正在使用RX:

import retrofit2.Response;
import rx.Observable;

public interface YourInterface {
  @GET("your_end_point")
  Observable<Response<GetArticlesResponse>> getArticles();
}
2.响应;
进口接收。可观察;
公共接口YourInterface{
@获取(“你的终点”)
可观察的getArticles();
}
创建一些POJO:

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;
}
类源代码{
字符串id;
字符串名;
}
班级文章{
来源;
字符串作者;
字符串标题;
字符串描述;
字符串url;
字符串urlToImage;
字符串数据;
}
类GetArticlesResponse{
字符串状态;
综合结果;
列出文章;
}
然后将GetArticles Response传递给您的改装呼叫

import retrofit2.Response;
import retrofit2.Call;
public interface YourInterface {
  @GET("your_end_point")
  Call<Response<GetArticlesResponse>> getArticles();
}
2.响应;
2.电话;;
公共接口YourInterface{
@获取(“你的终点”)
调用getArticles();
}
或者如果您正在使用RX:

import retrofit2.Response;
import rx.Observable;

public interface YourInterface {
  @GET("your_end_point")
  Observable<Response<GetArticlesResponse>> getArticles();
}
2.响应;
进口接收。可观察;
公共接口YourInterface{
@获取(“你的终点”)
可观察的getArticles();
}

将json转换为POJO并将其用于改装2.3

将json转换为POJO并将其用于改装2.3

如果您不知道需要创建多少类,只需在此处复制并粘贴json即可


这将帮助您并使您的工作变得轻松。

如果您不知道需要创建多少类,只需将json复制并粘贴到此处即可

这将帮助您并使您的工作变得轻松。

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;
}

}
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;
}

}
改装接口

public interface YourInterface {
@GET("whatever api u are using")
Call<MainClass> getData(@Query("whatever key") String/int(whatever name)) //or leave blank
}
公共接口YourInterface{
@GET(“您正在使用的任何api”)
调用getData(@Query(“任意键”)String/int(任意名称))//或留空
}
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;
}

}
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;
}

}
改装接口

public interface YourInterface {
@GET("whatever api u are using")
Call<MainClass> getData(@Query("whatever key") String/int(whatever name)) //or leave blank
}
公共接口YourInterface{
@GET(“您正在使用的任何api”)
调用getData(@Query(“任意键”)String/int(任意名称))//或留空
}

在使用改型时,我建议使用library,它将json解析为您应该创建的对象类型,因此首先您应该根据收到的响应创建一个表示您的对象的对象,这样在您的情况下就会像这样

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;
}
}
类似地,创建另一个类,即包含源对象的源类

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;
   }
 }
现在,在您的改型api代码中,您可以执行如下操作

 @GET("YOUR_ENDPOINT/")
 Call<JsonObject> getArticles(... put your required fields here example ...@Query("token") String token);
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
            }
        });
    }
@GET(“您的_端点/”)
调用getArticles(…在此处放置所需字段,例如…@Query(“token”)字符串token);
在你的活动中做一些类似的事情

 @GET("YOUR_ENDPOINT/")
 Call<JsonObject> getArticles(... put your required fields here example ...@Query("token") String token);
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
            }
        });
    }
List-mArticleList=newarraylist();
字符串mTotalResults=“”;
UserApi服务=ServiceGenerator.createService(UserApi.class);
调用结果=service.getArticles(令牌);
result.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.code()==200){
mArticleList=null;
JsonArray data=response.body().getAsJsonObject(“数据”).getAsJsonArray(“文章”);
mArticleList=new Gson().fromJson(data.toString(),new TypeToken(){}.getType());
mTotalResults=response.body().getAsJsonObject(“数据”).getAsString(“totalResults”);
//如果你想让它成为一个整数,你可以这样做
int totalResults=Integer.parseInt(mTotalResults);
//…用你的清单做你想做的事
//...
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
//做你必须做的事情以防出错
}
});
}

希望这有助于

在使用改型时,我建议使用library,它可以将json解析为您应该创建的对象类型,因此首先您应该根据收到的响应创建一个表示您的对象的对象,以便在您的情况下类似于此

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;
}
}
类似地,创建另一个类,即包含源对象的源类

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;
   }
 }
现在,在您的改型api代码中,您可以执行如下操作

 @GET("YOUR_ENDPOINT/")
 Call<JsonObject> getArticles(... put your required fields here example ...@Query("token") String token);
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
            }
        });
    }
@GET(“您的_端点/”)
调用getArticles(…在此处放置所需字段,例如…@Query(“token”)字符串token);
在你的活动中做一些类似的事情

 @GET("YOUR_ENDPOINT/")
 Call<JsonObject> getArticles(... put your required fields here example ...@Query("token") String token);
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
            }
        });
    }
List-mArticleList=newarraylist();
字符串mTotalResults=“”;
UserApi服务=ServiceGenerator.createService(UserApi.class);
调用结果=service.getArticles(令牌);
result.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.code()==200){
mArticleList=null;
JsonArray data=response.body().getAsJsonObject(“数据”).getAsJsonArray(“文章”);
mArticleList=new Gson().fromJson(data.toString(),new TypeToken(){}.getType());
mTotalResults=response.body().getAsJsonObject(“数据”).getAsString(“totalResults”);
//如果你想让它成为一个整数,你可以这样做
int totalResults=Integer.parseInt(mTotalResults);
//…用你的清单做你想做的事
//...
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
//做你必须做的事情以防出错
}
});
}

希望这有帮助

看来json数组是错误的。cl在哪里