Android将json数组添加到Pojo类

时间:2018-01-28 05:59:57

标签: java android gson

我已关注从服务器返回的JSON

{
  "matches": [
    {
      "unique_id": 1122278,
      "date": "2018-01-24T00:00:00.000Z",
      "team-2": "India",
      "team-1": "South Africa",
      "type": "Test",
      "dateTimeGMT": "2018-01-24T08:00:00.000Z",
      "squad": true,
      "toss_winner_team": "India",
      "matchStarted": true
    },
    {
      "unique_id": 1116929,
      "team-2": "India Under-19s",
      "team-1": "Bangladesh Under-19s",
      "type": "YouthODI",
      "date": "2018-01-25T00:00:00.000Z",
      "dateTimeGMT": "2018-01-25T21:30:00.000Z",
      "squad": true,
      "toss_winner_team": "India Under-19s",
      "winner_team": "India Under-19s",
      "matchStarted": true
    },

    {
      "unique_id": 1115781,
      "team-2": "England",
      "team-1": "New Zealand",
      "type": "Test",
      "date": "2018-03-29T00:00:00.000Z",
      "dateTimeGMT": "2018-03-29T22:00:00.000Z",
      "squad": false,
      "matchStarted": false
    }
  ],
  "v": "1",
  "ttl": 43,
  "provider": {
    "source": "Various",
    "url": "https://cricapi.com/",
    "pubDate": "2018-01-27T13:18:55.717Z"
  },
  "creditsLeft": 250
}

使用Volley librarygson

我正在尝试将JSON array match推送到Match Model(Pojo)。我想我可以使用循环插入它,但还有其他方法可以将所有JSON数组添加到模型中吗?

public class Main2Activity extends AppCompatActivity {

    RecyclerView recyclerView;
    ArrayList<Match> matches;
    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recylcer_1);

       recyclerView=(RecyclerView) findViewById(R.id.recyler);
        myAdapter=new MyAdapter(matches);
        RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAnimation(n);
        recyclerView.setAdapter(myAdapter);
        callCricket();
    }

    public void callCricket() {

        CallApi callApi = new CallApi();
        callApi.setVolleyInterface(new VolleyInterface() {
            @Override
            public void onSucess(String string) {
                Log.d("ApiCall_success", string);

                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<Match>>(){}.getType();
                JSONObject jsonObject = null;
                try {

                    jsonObject = new JSONObject(string);
                    JSONArray jsonArray = jsonObject.getJSONArray("matches");
                    matches.addAll(gson.fromJson(jsonArray,type));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String string) {

            }
        }); 
    }
}

我尝试使用gson,但收到错误。

1 个答案:

答案 0 :(得分:1)

使用jsonschema2pojo

按照您的JSON创建如下的pojo类

在GSON中有无需循环以在pojo类中插入数据。

<强> Example.java

 package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("matches")
@Expose
private List<Match> matches = null;
@SerializedName("v")
@Expose
private String v;
@SerializedName("ttl")
@Expose
private Integer ttl;
@SerializedName("provider")
@Expose
private Provider provider;
@SerializedName("creditsLeft")
@Expose
private Integer creditsLeft;

public List<Match> getMatches() {
return matches;
}

public void setMatches(List<Match> matches) {
this.matches = matches;
}

public String getV() {
return v;
}

public void setV(String v) {
this.v = v;
}

public Integer getTtl() {
return ttl;
}

public void setTtl(Integer ttl) {
this.ttl = ttl;
}

public Provider getProvider() {
return provider;
}

public void setProvider(Provider provider) {
this.provider = provider;
}

public Integer getCreditsLeft() {
return creditsLeft;
}

public void setCreditsLeft(Integer creditsLeft) {
this.creditsLeft = creditsLeft;
}

}

<强> Match.java

    package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Match {

@SerializedName("unique_id")
@Expose
private Integer uniqueId;
@SerializedName("date")
@Expose
private String date;
@SerializedName("team-2")
@Expose
private String team2;
@SerializedName("team-1")
@Expose
private String team1;
@SerializedName("type")
@Expose
private String type;
@SerializedName("dateTimeGMT")
@Expose
private String dateTimeGMT;
@SerializedName("squad")
@Expose
private Boolean squad;
@SerializedName("toss_winner_team")
@Expose
private String tossWinnerTeam;
@SerializedName("matchStarted")
@Expose
private Boolean matchStarted;
@SerializedName("winner_team")
@Expose
private String winnerTeam;

public Integer getUniqueId() {
return uniqueId;
}

public void setUniqueId(Integer uniqueId) {
this.uniqueId = uniqueId;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getTeam2() {
return team2;
}

public void setTeam2(String team2) {
this.team2 = team2;
}

public String getTeam1() {
return team1;
}

public void setTeam1(String team1) {
this.team1 = team1;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getDateTimeGMT() {
return dateTimeGMT;
}

public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}

public Boolean getSquad() {
return squad;
}

public void setSquad(Boolean squad) {
this.squad = squad;
}

public String getTossWinnerTeam() {
return tossWinnerTeam;
}

public void setTossWinnerTeam(String tossWinnerTeam) {
this.tossWinnerTeam = tossWinnerTeam;
}

public Boolean getMatchStarted() {
return matchStarted;
}

public void setMatchStarted(Boolean matchStarted) {
this.matchStarted = matchStarted;
}

public String getWinnerTeam() {
return winnerTeam;
}

public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}

}

<强> Provider.java

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Provider {

@SerializedName("source")
@Expose
private String source;
@SerializedName("url")
@Expose
private String url;
@SerializedName("pubDate")
@Expose
private String pubDate;

public String getSource() {
return source;
}

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

public String getUrl() {
return url;
}

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

public String getPubDate() {
return pubDate;
}

public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}

}

在您的Activity类中,执行以下编码:

public static final String TAG = DoctorHome.class.getSimpleName();
ArrayList<DoctorsCatPojo> doctorCatList = new ArrayList<>();
DoctorsCatAdapter doctorsCatAdapter;
RecyclerView recyclerView;



 private void getDoctorCategory() {
    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();
    String url = Constant.DOCTOR_CATEGORY;
    Log.e("URL",""+url);

    JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("onResponse",""+response);
                    try {
                        status = response.getString("status");
                        if(status.equals("success")){
                            String info = response.getString("list");
                            JSONArray jsonArray = new JSONArray(info);

                            Gson gson = new Gson();
                            Type listType = new TypeToken<ArrayList<DoctorsCatPojo>>() {
                            }.getType();
                            doctorCatList = gson.fromJson(jsonArray.toString(), listType);

                            if(doctorCatList!=null && doctorCatList.size()!=0){
                                doctorsCatAdapter = new DoctorsCatAdapter(DoctorHome.this,doctorCatList);
                                recyclerView.setAdapter(doctorsCatAdapter);
                                Log.d(TAG, response.toString());
                            }


                        }
                        else {
                            message = response.getString("message");
                            // Toast.makeText(getApplicationContext(),""+message,Toast.LENGTH_SHORT).show();
                            pDialog.hide();
                        }



                    } catch (Exception e) {
                        Log.e("Exception",""+e);
                        e.printStackTrace();
                    }
                    pDialog.hide();




                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e("error",""+error.getMessage());
            pDialog.hide();
        }
    });
    AppController.getInstance(DoctorHome.this).addToRequestQueue(request, "doctor_category");


}

你的适配器类将是这样的:

public class DoctorsCatAdapter extends RecyclerView.Adapter<DoctorsCatAdapter.MyViewHolder> {
    ArrayList <DoctorsCatPojo> doctorCatList;
    Context context;

    public DoctorsCatAdapter( Context context,ArrayList<DoctorsCatPojo> doctorCatList) {
         this.doctorCatList = doctorCatList;
        this.context= context;
    }




    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctors_category_row, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        DoctorsCatPojo doc = doctorCatList.get(position);
      //  holder.doctorsCatImg.setImageURI(doc.getCategory_img());



        if(doc.getCategory_name()!=null){
            holder.doctorsCatName.setText(doc.getCategory_name());
        }
        if(doc.getCategory_img()!=null){
            Picasso.with(context)
                    .load(doc.getCategory_img().replace(" ", "%20").trim())
                    .placeholder(R.drawable.no_image)
                    .into(holder.doctorsCatImg);

        }








    }

    @Override
    public int getItemCount() {
        return doctorCatList.size();
    }

     class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
         ImageView doctorsCatImg;
         TextView doctorsCatName;

         MyViewHolder(final View view) {
            super(view);
            itemView.setOnClickListener(this);

            doctorsCatImg = (ImageView)view.findViewById(R.id.doctorsCatImg);
            doctorsCatName = (TextView) view.findViewById(R.id.doctorsCatName);

        }


         @Override
         public void onClick(View view) {
             doctorCatList.get(getPosition()).getCategory_id();
             ((DoctorHome)context).callDoctorListActivity(doctorCatList.get(getPosition()).getCategory_id(),doctorCatList.get(getPosition()).getCategory_name());
         }
     }
}