Android 如何在json对象mvvm中解析json数组
我有一个json,里面有一个对象我有一个json数组我制作了pojo,但和mvvm一样,我不知道如何解析它并在recyclerView(片段)中显示它。请检查我的代码,谢谢 这是我的jsonAndroid 如何在json对象mvvm中解析json数组,android,json,mvvm,retrofit2,Android,Json,Mvvm,Retrofit2,我有一个json,里面有一个对象我有一个json数组我制作了pojo,但和mvvm一样,我不知道如何解析它并在recyclerView(片段)中显示它。请检查我的代码,谢谢 这是我的json { "response":{ "status":"ok", "userTier":"developer", "total":2157516, "startIndex":1, "pageSize":10, "currentPage":1, "pages":215752, "
{
"response":{
"status":"ok",
"userTier":"developer",
"total":2157516,
"startIndex":1,
"pageSize":10,
"currentPage":1,
"pages":215752,
"orderBy":"newest",
"results":[
{
"id":"uk-news/2019/dec/02/killer-of-three-elderly-devon-men-found-not-guilty-due-to-insanity",
"type":"article",
"sectionId":"uk-news",
"sectionName":"UK news",
"webPublicationDate":"2019-12-02T17:53:26Z",
"webTitle":"Killer of three elderly Devon men found not guilty due to insanity",
"webUrl":"https://www.theguardian.com/uk-news/2019/dec/02/killer-of-three-elderly-devon-men-found-not-guilty-due-to-insanity",
"apiUrl":"https://content.guardianapis.com/uk-news/2019/dec/02/killer-of-three-elderly-devon-men-found-not-guilty-due-to-insanity",
"isHosted":false,
"pillarId":"pillar/news",
"pillarName":"News"
},
{
"id":"football/2019/dec/02/fa-homophobic-chants-west-ham-chelsea-kick-it-out",
"type":"article",
"sectionId":"football",
"sectionName":"Football",
"webPublicationDate":"2019-12-02T17:53:09Z",
"webTitle":"FA in discussions after homophobic chants by West Hams fans",
"webUrl":"https://www.theguardian.com/football/2019/dec/02/fa-homophobic-chants-west-ham-chelsea-kick-it-out",
"apiUrl":"https://content.guardianapis.com/football/2019/dec/02/fa-homophobic-chants-west-ham-chelsea-kick-it-out",
"isHosted":false,
"pillarId":"pillar/sport",
"pillarName":"Sport"
},
{
"id":"news/shortcuts/2019/dec/02/jeremy-corbyn-suit-fabric-labour-leader-for-the-many-not-the-few-pinstripes",
"type":"article",
"sectionId":"politics",
"sectionName":"Politics",
"webPublicationDate":"2019-12-02T17:42:03Z",
"webTitle":"Socialist pinstripe: the secret message stitched into Jeremy Corbyn’s new suit",
"webUrl":"https://www.theguardian.com/news/shortcuts/2019/dec/02/jeremy-corbyn-suit-fabric-labour-leader-for-the-many-not-the-few-pinstripes",
"apiUrl":"https://content.guardianapis.com/news/shortcuts/2019/dec/02/jeremy-corbyn-suit-fabric-labour-leader-for-the-many-not-the-few-pinstripes",
"isHosted":false,
"pillarId":"pillar/news",
"pillarName":"News"
},
{
"id":"uk-news/2019/dec/02/police-criticised-response-attack-rabbi-in-north-london",
"type":"article",
"sectionId":"uk-news",
"sectionName":"UK news",
"webPublicationDate":"2019-12-02T17:41:13Z",
"webTitle":"Police criticised over response to attack on rabbi in north London",
"webUrl":"https://www.theguardian.com/uk-news/2019/dec/02/police-criticised-response-attack-rabbi-in-north-london",
"apiUrl":"https://content.guardianapis.com/uk-news/2019/dec/02/police-criticised-response-attack-rabbi-in-north-london",
"isHosted":false,
"pillarId":"pillar/news",
"pillarName":"News"
},
{
"id":"artanddesign/2019/dec/02/les-tasses-war-and-pissoirs-how-the-debauched-urinals-of-paris-helped-to-beat-the-nazis",
"type":"article",
"sectionId":"artanddesign",
"sectionName":"Art and design",
"webPublicationDate":"2019-12-02T17:36:28Z",
"webTitle":"War and pissoirs: how the urinals of Paris helped beat the Nazis",
"webUrl":"https://www.theguardian.com/artanddesign/2019/dec/02/les-tasses-war-and-pissoirs-how-the-debauched-urinals-of-paris-helped-to-beat-the-nazis",
"apiUrl":"https://content.guardianapis.com/artanddesign/2019/dec/02/les-tasses-war-and-pissoirs-how-the-debauched-urinals-of-paris-helped-to-beat-the-nazis",
"isHosted":false,
"pillarId":"pillar/arts",
"pillarName":"Arts"
},
{
"id":"commentisfree/2019/dec/02/trust-in-politics-has-evaporated-now-it-offers-only-fantasy",
"type":"article",
"sectionId":"commentisfree",
"sectionName":"Opinion",
"webPublicationDate":"2019-12-02T17:36:01Z",
"webTitle":"Trust in politics has evaporated, now it offers only fantasy | Suzanne Moore",
"webUrl":"https://www.theguardian.com/commentisfree/2019/dec/02/trust-in-politics-has-evaporated-now-it-offers-only-fantasy",
"apiUrl":"https://content.guardianapis.com/commentisfree/2019/dec/02/trust-in-politics-has-evaporated-now-it-offers-only-fantasy",
"isHosted":false,
"pillarId":"pillar/opinion",
"pillarName":"Opinion"
},
{
"id":"film/2019/dec/02/2019-braddies-peter-bradshaw-films-of-the-year",
"type":"article",
"sectionId":"film",
"sectionName":"Film",
"webPublicationDate":"2019-12-02T17:29:48Z",
"webTitle":"And the 2019 Braddies go to … Peter Bradshaw's film picks of the year",
"webUrl":"https://www.theguardian.com/film/2019/dec/02/2019-braddies-peter-bradshaw-films-of-the-year",
"apiUrl":"https://content.guardianapis.com/film/2019/dec/02/2019-braddies-peter-bradshaw-films-of-the-year",
"isHosted":false,
"pillarId":"pillar/arts",
"pillarName":"Arts"
},
{
"id":"world/2019/dec/02/christine-lagarde-ecb-should-do-more-to-tackle-climate-emergency",
"type":"article",
"sectionId":"world",
"sectionName":"World news",
"webPublicationDate":"2019-12-02T17:23:28Z",
"webTitle":"Lagarde: ECB should do more to tackle climate emergency",
"webUrl":"https://www.theguardian.com/world/2019/dec/02/christine-lagarde-ecb-should-do-more-to-tackle-climate-emergency",
"apiUrl":"https://content.guardianapis.com/world/2019/dec/02/christine-lagarde-ecb-should-do-more-to-tackle-climate-emergency",
"isHosted":false,
"pillarId":"pillar/news",
"pillarName":"News"
},
{
"id":"food/2019/dec/02/robert-neame-obituary",
"type":"article",
"sectionId":"food",
"sectionName":"Food",
"webPublicationDate":"2019-12-02T17:19:32Z",
"webTitle":"Robert Neame obituary",
"webUrl":"https://www.theguardian.com/food/2019/dec/02/robert-neame-obituary",
"apiUrl":"https://content.guardianapis.com/food/2019/dec/02/robert-neame-obituary",
"isHosted":false,
"pillarId":"pillar/lifestyle",
"pillarName":"Lifestyle"
},
{
"id":"politics/live/2019/dec/02/general-election-swinson-condemns-johnson-over-trump-friendship-ahead-of-london-visit-live",
"type":"liveblog",
"sectionId":"politics",
"sectionName":"Politics",
"webPublicationDate":"2019-12-02T17:13:40Z",
"webTitle":"General election: Johnson insists he opposed early release for terrorists long before London Bridge attack – live news",
"webUrl":"https://www.theguardian.com/politics/live/2019/dec/02/general-election-swinson-condemns-johnson-over-trump-friendship-ahead-of-london-visit-live",
"apiUrl":"https://content.guardianapis.com/politics/live/2019/dec/02/general-election-swinson-condemns-johnson-over-trump-friendship-ahead-of-london-visit-live",
"isHosted":false,
"pillarId":"pillar/news",
"pillarName":"News"
}
]
}
}
这是我的pojo课程
public class NewsResponse {
@SerializedName("response")
private NewsArticle response;
public NewsArticle getResponse() {
return response;
}
public void setResponse(NewsArticle response) {
this.response = response;
}
}
这是我的新仓库
public class NewsRepository {
private static NewsRepository newsRepository;
public static NewsRepository getInstance(){
if (newsRepository == null){
newsRepository = new NewsRepository();
}
return newsRepository;
}
private NewsApi newsApi;
public NewsRepository(){
newsApi = RetrofitService.cteateService(NewsApi.class);
}
public MutableLiveData<NewsResponse> getNews(String key){
final MutableLiveData<NewsResponse> newsData = new MutableLiveData<>();
newsApi.getNewsList( key).enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call,
Response<NewsResponse> response) {
if (response.isSuccessful()){
newsData.setValue(response.body());
}
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
newsData.setValue(null);
}
});
return newsData;
}
}
公共类新闻存储库{
私有静态新闻存储库;
公共静态新闻存储库getInstance(){
if(newsRepository==null){
newsRepository=新的newsRepository();
}
返回新闻存储库;
}
私人新闻API;
公共新闻存储库(){
newsApi=reformationservice.cteateService(newsApi.class);
}
公共可变LiveData getNews(字符串键){
final MutableLiveData newsData=新的MutableLiveData();
newsApi.getNewsList(key.enqueue)(新回调()命令){
@凌驾
公共void onResponse(调用,
回应(回应){
if(response.issusccessful()){
newsData.setValue(response.body());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
newsData.setValue(null);
}
});
返回新闻数据;
}
}
现在来看片段
ublic class NewsFragment extends Fragment {
ArrayList<NewsResponse> articleArrayList = new ArrayList<>();
NewsAdapter newsAdapter;
RecyclerView rvHeadline;
private static final String TAG = "NewsFragment";
private PageViewModel pageViewModel;
public NewsFragment() {
// Required empty public constructor
}
/**
* @return A new instance of fragment SpeedDialFragment.
*/
public static NewsFragment newInstance() {
return new NewsFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.news_fragment, container, false);
rvHeadline = root.findViewById(R.id.rvNews);
pageViewModel.init();
pageViewModel.getNewsRepository().observe(this, new Observer<NewsResponse>() {
@Override
public void onChanged(NewsResponse newsResponse) {
** ****** List<NewsArticle> newsArticles = newsResponse.getResponse(); ******
******* articleArrayList.addAll(newsArticles); ********
newsAdapter.notifyDataSetChanged();
}
});
setupRecyclerView();
return root;
}
private void setupRecyclerView() {
if (newsAdapter == null) {
newsAdapter = new NewsAdapter(getActivity(), articleArrayList);
rvHeadline.setLayoutManager(new LinearLayoutManager(getActivity()));
rvHeadline.setAdapter(newsAdapter);
rvHeadline.setItemAnimator(new DefaultItemAnimator());
rvHeadline.setNestedScrollingEnabled(true);
} else {
newsAdapter.notifyDataSetChanged();
}
}
}
public类新闻片段扩展片段{
ArrayList Article ArrayList=新的ArrayList();
新闻适配器;
回收视图标题;
私有静态最终字符串TAG=“NewsFragment”;
私有页面视图模型页面视图模型;
公共新闻片段(){
//必需的空公共构造函数
}
/**
*@返回碎片SpeedDialFragment的新实例。
*/
公共静态新闻片段newInstance(){
返回新的新闻片段();
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
pageViewModel=ViewModelProviders.of(this.get)(pageViewModel.class);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
视图根=充气机。充气(R.layout.news\u片段,容器,false);
rvHeadline=root.findviewbyd(R.id.rvNews);
pageViewModel.init();
pageViewModel.getNewsRepository().observe(这是新的观察者(){
@凌驾
更改后的公共无效(NewsResponse NewsResponse){
********列出newsArticles=newsResponse.getResponse()******
*******articleArrayList.addAll(新闻文章)********
newsAdapter.notifyDataSetChanged();
}
});
setupRecyclerView();
返回根;
}
私有void setupRecyclerView(){
if(newsAdapter==null){
newsAdapter=新的newsAdapter(getActivity(),articleArrayList);
rvHeadline.setLayoutManager(新的LinearLayoutManager(getActivity());
rvHeadline.setAdapter(新闻适配器);
rvHeadline.setItemAnimator(新的DefaultItemAnimator());
rvHeadline.setNestedScrollingEnabled(true);
}否则{
newsAdapter.notifyDataSetChanged();
}
}
}
我的错误在pageViewModel.getNewsRepository()中,我不知道该怎么办
如果我将泛型更改为结果类,第一行中的错误已修复,但第二行无法接受结果中的列表,我丢失了,请帮助
ViewModel类
public class PageViewModel extends ViewModel {
private MutableLiveData<NewsResponse> mutableLiveData;
private NewsRepository newsRepository;
public void init(){
if (mutableLiveData != null){
return;
}
newsRepository = NewsRepository.getInstance();
mutableLiveData = newsRepository.getNews( "***************");
}
public LiveData<NewsResponse> getNewsRepository() {
return mutableLiveData;
}
}
公共类PageViewModel扩展了ViewModel{
私有MutableLiveData MutableLiveData;
私有新闻存储库新闻存储库;
公共void init(){
if(mutableLiveData!=null){
返回;
}
newsRepository=newsRepository.getInstance();
mutableLiveData=newsRepository.getNews(“*******************”);
}
公共LiveData getNewsRepository(){
返回可变的livedata;
}
}
直接传递新闻存储库的MutableLiveData
以从您的视图模型查看
public class PageViewModel extends ViewModel {
private NewsRepository newsRepository = NewsRepository.getInstance();
public MutableLiveData<NewsResponse> getNewsRepository() {
return newsRepository.getNews( "***************");
}
}
编辑
我把名单改成了结果
ArrayList<Result> articleArrayList = new ArrayList<>();
ArrayList articleAraylist=new ArrayList();
而且我在这里换的
@Override
public void onChanged(NewsResponse newsResponse) {
List<Result> newsArticles = newsResponse.getResponse().getResults();
articleArrayList.addAll(newsArticles);
@覆盖
更改后的公共无效(NewsResponse NewsResponse){
List newsArticles=newsResponse.getResponse().getResults();
articleArrayList.addAll(新闻文章);
就像Md.Asaduzzaman说的那样,我也改变了适配器,一切都正常了你的ViewModel代码在哪里?我编辑了它我的ViewModel类OK,我把它放在这里,就像你还是一样的问题:@Override public void onChanged(NewsResponse NewsResponse){List newsactions=NewsResponse.getResponse().getResponse().getResults();articleArrayList.addAll(newsArticles);您能为我提供一个代码帮助吗这是我第一次使用MVVM,现在有什么问题吗?onChanged
是否执行?我在那里有错误(必需列表(newsArticle)找到列表(Result)),这里列出newsArticles=newsResponse.getResponse().getResults()@MikeB,检查我的更新答案,并用结果更新适配器
public class NewsFragment extends Fragment {
ArrayList<Result> ArrayList = new ArrayList<>();
....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
pageViewModel.getNewsRepository().observe(this, new Observer<NewsResponse>() {
@Override
public void onChanged(NewsResponse newsResponse) {
articleArrayList = newsResponse.getResponse().getResults();
newsAdapter.notifyDataSetChanged();
}
});
....
}
private void setupRecyclerView() {
if (newsAdapter == null) {
newsAdapter = new NewsAdapter(getActivity(), resultArrayList);
rvHeadline.setLayoutManager(new LinearLayoutManager(getActivity()));
rvHeadline.setAdapter(newsAdapter);
rvHeadline.setItemAnimator(new DefaultItemAnimator());
rvHeadline.setNestedScrollingEnabled(true);
} else {
newsAdapter.notifyDataSetChanged();
}
}
}
ArrayList<Result> articleArrayList = new ArrayList<>();
@Override
public void onChanged(NewsResponse newsResponse) {
List<Result> newsArticles = newsResponse.getResponse().getResults();
articleArrayList.addAll(newsArticles);