How to deserialize a JSON Object in a multidimensional array - java

I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}

JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");

Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}

Related

The request sent by the client was syntactically incorrect. Spring Backend

I stuck at this problem with Post Request, which gives me error 400 bad request, i have checked the JSON RequestBody via okHttpInterceptor by Retrofit and Json validated correctly. I don't know what's the problem with requestBody. it works with ModelAttribute though, but i want to pass data as requestBody.
This is my Spring Controller ->
#RequestMapping(value = "/updateProfile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public BasicResponse farmerUpdateProfile(#RequestBody UpdateFarmerRequest updateFarmerRequest, HttpServletRequest request) {
BasicResponse response = new BasicResponse();
// get authentication token and farmer ID from header
String requestAuthToken = (String) request.getHeader(MOBILE_AUTH);
String requestFarmerId = (String) request.getHeader(FARMER_ID);
// update farmer data, if id and AuthTokens are same...
// Validate Authentication Token
try {
if (!farmerMobileManager.validateAuthToken(requestFarmerId, requestAuthToken)) {
response.setErrorCode(ErrorCode.BAD_CREDENTIALS);
response.setResponse("Bad request error");
return response;
}
farmerMobileManager.updateFarmerRequest(updateFarmerRequest, response, requestFarmerId);
} catch (Exception ex) {
System.out.println(ex.getMessage());
response.setErrorCode(ErrorCode.INTERNAL_SERVER_ERROR);
response.setResponse("Error fetching prescriptions");
}
return response;
}
This is my UpdateFarmerRequestClass.
public class UpdateFarmerRequest {
#JsonProperty("farmer")
private Farmer farmer;
public void setFarmer(Farmer farmer) {
this.farmer = farmer;
}
public Farmer getFarmer() {
return farmer;
}
}
This is my Farmerclass ->
public class Farmer extends User {
private String farmerReferenceId;
private String cropId;
private String nomineeName;
private NomineeRelation nomineeRelation;
private String stateName;
private String mandalName;
private String villageName;
private String houseNumber;
private Boolean smartPhoneUser;
private SocialStatus socialStatus;
private EducationLevel educationLevel;
private String aadharNumber;
private String stateId;
private String districtId;
private String mandalId;
private String villageId;
private Boolean oneTimeDataEntered = false;
private ArrayList<CropData> cropData;
public String getHouseNumber() {
return houseNumber;
}
public String getCropId() {
return cropId;
}
public void setCropId(String cropId) {
this.cropId = cropId;
}
public List<CropData> getCropData() {
return cropData;
}
public void setCropData(List<CropData> cropData) {
List<CropData> newCropData = new ArrayList<>();
for (CropData cropDataItem : cropData) {
Boolean didFind = false;
for (CropData farmerCropData : this.cropData) {
// if it matched in db, update the record.
if (farmerCropData.getCrop().name().equals(cropDataItem.getCrop().name())) {
// update that you got the db record
didFind = true;
farmerCropData.setCropAcres(cropDataItem.getCropAcres());
farmerCropData.setCropName(cropDataItem.getCropName());
farmerCropData.setCropYield(cropDataItem.getCropYield());
}
}
if (!didFind) {
// if you didn't fnd the record, add to new crop data
newCropData.add(cropDataItem);
}
this.cropData.addAll(newCropData);
}
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Farmer() {
super();
}
public String getNomineeName() {
return nomineeName;
}
public void setNomineeName(String nomineeName) {
this.nomineeName = nomineeName;
}
public NomineeRelation getNomineeRelation() {
return nomineeRelation;
}
public void setNomineeRelation(NomineeRelation nomineeRelation) {
this.nomineeRelation = nomineeRelation;
}
public String getMandalName() {
return mandalName;
}
public void setMandalName(String mandalName) {
this.mandalName = mandalName;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public Boolean getSmartPhoneUser() {
return smartPhoneUser;
}
public void setSmartPhoneUser(Boolean smartPhoneUser) {
this.smartPhoneUser = smartPhoneUser;
}
public SocialStatus getSocialStatus() {
return socialStatus;
}
public void setSocialStatus(SocialStatus socialStatus) {
this.socialStatus = socialStatus;
}
public EducationLevel getEducationLevel() {
return educationLevel;
}
public void setEducationLevel(EducationLevel educationLevel) {
this.educationLevel = educationLevel;
}
public String getAadharNumber() {
return aadharNumber;
}
public void setAadharNumber(String aadharNumber) {
this.aadharNumber = aadharNumber;
}
public String getFarmerReferenceId() {
return farmerReferenceId;
}
public void setFarmerReferenceId(String farmerReferenceId) {
this.farmerReferenceId = farmerReferenceId;
}
public String getStateId() {
return stateId;
}
public void setStateId(String stateId) {
this.stateId = stateId;
}
public String getDistrictId() {
return districtId;
}
public void setDistrictId(String districtId) {
this.districtId = districtId;
}
public String getMandalId() {
return mandalId;
}
public void setMandalId(String mandalId) {
this.mandalId = mandalId;
}
public String getVillageId() {
return villageId;
}
public void setVillageId(String villageId) {
this.villageId = villageId;
}
public Boolean getOneTimeDataEntered() {
return oneTimeDataEntered;
}
public void setOneTimeDataEntered(Boolean oneTimeDataEntered) {
this.oneTimeDataEntered = oneTimeDataEntered;
}
public List<String> collectErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
// if (StringUtils.isEmpty(this.nomineeName)) {
// errors.add("nomineeName");
// }
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public List<String> collectSignUpErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public static class Constants extends User.Constants {
public static final String FARMER_REFERENCE_ID = "farmerReferenceId";
public static final String AADHAR_NUMBER = "aadharNumber";
public static final String MANDAL_ID = "mandalId";
public static final String VILLAGE_ID = "villageId";
public static final String FARMER_ID = "_id";
}
}
this is my RequestBody that i am sending in POSTMAN.
RequestBody ->
{
"farmer": {
"city": "",
"mandalName": "",
"stateName": "",
"villageName": "",
"countryCode": "+",
"cropData": [{
"crop": "RICE",
"cropAcres": 1.0,
"cropName": "RICE",
"cropYield": 2.0
}, {
"crop": "PADDY",
"cropAcres": 4.0,
"cropName": "PADDY",
"cropYield": 5.0
}
],
"cropId": "",
"districtId": "",
"farmerReferenceId": "",
"firstName": "",
"houseNumber": "",
"id": "",
"mandalId": "",
"phoneNumber": "",
"stateId": "",
"villageId": ""
}
}
The Data are not empty, but i am purposely not filling it for privacy purpose.
I have solved my problem, it was naming convention problem, as i was passing cropData as "cropData", while at server Side it was "CropData."

How to parse json when curly braces inside quotation mark?

How to parse this kind of json?
{
"tId": 5439661,
"name": "aASD",
"inputParameters": {
"a": "50",
"b": "234324",
"c": "wefefew",
"d": "T",
"e": "4224",
"f": "T",
"g": "t"
},
"outputParameters": {
"dId": "{1234435-A333F-A3334-A273-123243252355}",
"fd": "1000023456"
}
}
Parsing code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
I tried like above but I get this error:
org.json.JSONException: Expected ':' after 1234435-A333F-A3334-A273-123243252355
I tried with POJO and gson library but still with no success
Anybody has solved this kind of problem?
How can I get "dId" as string?
Edited: Posted response from server for testing
Use this Model:-
And use Gson First Include library of Gson Before using it
dependencies {
implementation 'com.google.code.gson:gson:2.8.2' // Old 2.8.0
}
Gson gson = new Gson();
RootObject rootObject = new RootObject();
rootObject = gson.fromJson("Your json string or content", RootObject.class)
public class InputParameters
{
private String a;
public String getA() { return this.a; }
public void setA(String a) { this.a = a; }
private String b;
public String getB() { return this.b; }
public void setB(String b) { this.b = b; }
private String c;
public String getC() { return this.c; }
public void setC(String c) { this.c = c; }
private String d;
public String getD() { return this.d; }
public void setD(String d) { this.d = d; }
private String e;
public String getE() { return this.e; }
public void setE(String e) { this.e = e; }
private String f;
public String getF() { return this.f; }
public void setF(String f) { this.f = f; }
private String g;
public String getG() { return this.g; }
public void setG(String g) { this.g = g; }
}
public class OutputParameters
{
private String dId;
public String getDId() { return this.dId; }
public void setDId(String dId) { this.dId = dId; }
private String fd;
public String getFd() { return this.fd; }
public void setFd(String fd) { this.fd = fd; }
}
public class RootObject
{
private int tId;
public int getTId() { return this.tId; }
public void setTId(int tId) { this.tId = tId; }
private String name;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
private InputParameters inputParameters;
public InputParameters getInputParameters() { return this.inputParameters; }
public void setInputParameters(InputParameters inputParameters) { this.inputParameters = inputParameters; }
private OutputParameters outputParameters;
public OutputParameters getOutputParameters() { return this.outputParameters; }
public void setOutputParameters(OutputParameters outputParameters) { this.outputParameters = outputParameters; }
}
Just write
String text= response.getString("dId");
and then text will be: {1234-123423-53235423} and you can do every thing with this text.
I solve your problem with this code example and my code work fine.
public void getjson() {
RequestQueue mQueue;
mQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.mocky.io/v2/5b28ca862f00006300f55e6e";
JsonObjectRequest request = new JsonObjectRequest(com.android.volley.Request.Method.GET, url, null, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
if(response.length()>0){
String id=response.getString("tId");
String name=response.getString("name");
Log.d("response.getid",id);
Log.d("response.getname",name);
JSONObject inputObject=response.getJSONObject("inputParameters");
if(inputObject.length()>0){
String a=inputObject.getString("a");
String b=inputObject.getString("b");
String c=inputObject.getString("c");
String d=inputObject.getString("d");
String e=inputObject.getString("e");
String f=inputObject.getString("f");
String g=inputObject.getString("g");
}
JSONObject outObject=response.getJSONObject("outputParameters");
if(outObject.length()>0){
String didText=outObject.getString("dId");
String fdText=outObject.getString("fd");
Log.d("response.getstring",didText);
Log.d("response.getstring",fdText);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", "Error de response");
error.printStackTrace();
}
});
mQueue.add(request);
}

Retrofit2: Expected a string but was BEGIN_ARRAY (Android Studio)

I have an error when retrieving json data with retrofit2 in Android Studio. Last time i was try to retrieving data with json only 1 Response model, but now i just need to retrieving json data more than 1 table from database.
Error
java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 20 path $.pesan
No adapter attached; skipping layout
My ResponseModel.class
public class ResponseModel {
String kode, pesan;
List<QuestionModel> result_question; //But the problem is coming when i try to retrieving another json from another table(2)
List<UserDataModel> result; //i was success with this(1)
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<QuestionModel> getResult_question() {
return result_question;
}
public void setResult_question(List<QuestionModel> result_question) {
this.result_question = result_question;
}
public List<UserDataModel> getResult() {
return result;
}
public void setResult(List<UserDataModel> result) {
this.result = result;
}
}
My QuestionModel.class
public class QuestionModel {
String id_question, id_user, judul, waktu, tanggal, jml_like, aktif;
public String getId_question() {
return id_question;
}
public void setId_question(String id_question) {
this.id_question = id_question;
}
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJml_like() {
return jml_like;
}
public void setJml_like(String jml_like) {
this.jml_like = jml_like;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
My ApiRequest
#GET(url_question_list)
Call<ResponseModel> getQuestionData();
Enqueu
getData.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
pd.dismiss();
Log.d(TAG,"onResponse: "+ response.body().getKode());
mList = response.body().getResult_question();
mAdapter = new AdapterQuestion(MainActivity.this, mList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
pd.dismiss();
Log.e(TAG, "onFailure: "+t.getMessage());
}
});
JSON Format
{
"kode": 1,
"pesan": [
{
"id_question": "2",
"id_user": "8",
"judul": "Title1",
"waktu": "11:22:10",
"tanggal": "20-06-2018",
"jml_like": "0",
"aktif": "Y"
},
{
"id_question": "1",
"id_user": "9",
"judul": "Title2",
"waktu": "11:22:20",
"tanggal": "19-02-2012",
"jml_like": "1",
"aktif": "Y"
}
]
}
Thank for your help.
UPDATE: SOLVED
'Pesan' should be List<>
In your ResponseModel you define String pesan, while in the json file pesan is a List<QuestionModel>
make some changes in response model class like below ..
public class Response {
#SerializedName("kode")
private Integer kode;
#SerializedName("pesan")
private List<Pesan> pesan = null;
public Integer getKode() {
return kode;
}
public void setKode(Integer kode) {
this.kode = kode;
}
public List<Pesan> getPesan() {
return pesan;
}
public void setPesan(List<Pesan> pesan) {
this.pesan = pesan;
}
}
and also make one pesan pojo class.
public class Pesan {
#SerializedName("id_question")
private String idQuestion;
#SerializedName("id_user")
private String idUser;
#SerializedName("judul")
private String judul;
#SerializedName("waktu")
private String waktu;
#SerializedName("tanggal")
private String tanggal;
#SerializedName("jml_like")
private String jmlLike;
#SerializedName("aktif")
private String aktif;
public String getIdQuestion() {
return idQuestion;
}
public void setIdQuestion(String idQuestion) {
this.idQuestion = idQuestion;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJmlLike() {
return jmlLike;
}
public void setJmlLike(String jmlLike) {
this.jmlLike = jmlLike;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
above code working only you provide json format in question if any error then pl provide full json from server given response.
because answer is based on question json format based.

json data should be print in specified textview

I have json data regarding student details,That i want to print in respective textviews. i'm new to json services please help me to print the this data on screen.I'm using getters and setters for subject score so further i want to use them dynamically.
here is my json data
{
"studentInfo": {
"studentName": "srini#gmail.com",
"studentId": "abc",
"date": 14102017,
"JanuaryScoreCard" : {
"english" : "44",
"Science" : "45",
"maths": "66",
"social" : "56",
"hindi" : "67",
"kannada" : "78",
},
"MarchScoreCard" : {
" english " : "54",
" Science " : "56",
" maths ": "70",
" social " : "87",
" hindi " : "98",
" kannada " : "56"
},
"comments" : ""
}
I'm Something to print but could not,i don't where i'm going wrong
public void init()
{
try {
parseJSON();
} catch (JSONException e)
{
e.printStackTrace();
}
}
public void parseJSON() throws JSONException{
jsonObject = new JSONObject(strJson);
JSONObject object = jsonObject.getJSONObject("studentInfo");
patientName = object.getString("studentName");
patientID = object.getString("studentId");
mName.setText(studentName);
mUserId.setText(studentId);
}
You can use JSON parser and then you can print any data you want from that,
Use GSON for this, here is an example https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a basic JSON Parsing process
public void parseJson() {
String your_response = "replace this with your response";
try {
JSONObject jsonObject = new JSONObject(your_response);
JSONObject studentInfoJsonObject = jsonObject.getJSONObject("studentInfo");
StudentInfo studentInfo1 = new StudentInfo();
studentInfo1.setStudentName(studentInfoJsonObject.optString("studentName"));
studentInfo1.setStudentId(studentInfoJsonObject.optString("studentId"));
studentInfo1.setDate(studentInfoJsonObject.optString("date"));
studentInfo1.setComments(studentInfoJsonObject.optString("comments"));
JSONObject januaryScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
JanuaryScoreCard januaryScoreCard1 = new JanuaryScoreCard();
januaryScoreCard1.setEnglish(januaryScoreCardJsonObject.optString("english"));
januaryScoreCard1.setHindi(januaryScoreCardJsonObject.optString("hindi"));
januaryScoreCard1.setMaths(januaryScoreCardJsonObject.optString("maths"));
januaryScoreCard1.setSocial(januaryScoreCardJsonObject.optString("social"));
januaryScoreCard1.setKannada(januaryScoreCardJsonObject.optString("kannada"));
januaryScoreCard1.setScience(januaryScoreCardJsonObject.optString("Science"));
JSONObject marchScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
MarchScoreCard marchScoreCard = new MarchScoreCard();
marchScoreCard.setEnglish(marchScoreCardJsonObject.optString("english"));
marchScoreCard.setHindi(marchScoreCardJsonObject.optString("hindi"));
marchScoreCard.setMaths(marchScoreCardJsonObject.optString("maths"));
marchScoreCard.setSocial(marchScoreCardJsonObject.optString("social"));
marchScoreCard.setKannada(marchScoreCardJsonObject.optString("kannada"));
marchScoreCard.setScience(marchScoreCardJsonObject.optString("Science"));
studentInfo1.setJanuaryScoreCard(januaryScoreCard1);
studentInfo1.setMarchScoreCard(marchScoreCard);
} catch (JSONException e) {
e.printStackTrace();
}
}
Student Info Class
public class StudentInfo {
private String studentName;
private String studentId;
private String date;
private String comments;
private JanuaryScoreCard januaryScoreCard;
private MarchScoreCard marchScoreCard;
public JanuaryScoreCard getJanuaryScoreCard() {
return januaryScoreCard;
}
public void setJanuaryScoreCard(JanuaryScoreCard januaryScoreCard) {
this.januaryScoreCard = januaryScoreCard;
}
public MarchScoreCard getMarchScoreCard() {
return marchScoreCard;
}
public void setMarchScoreCard(MarchScoreCard marchScoreCard) {
this.marchScoreCard = marchScoreCard;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
and Here is January class
public class JanuaryScoreCard {
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
and Here is March Class
public class MarchScoreCard{
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
You need to parse this json Data , For this you need Create appropriate bean classes and put data while parsing json into this bean classes object and create List .
Then you need to create ListView and Adapter for populate data into Screen or Activity.

Model Class for the given GoogleBooks API

I am new to android and I am creating an app to learn JSON Parsing. I want to parse the Google Books API's JSON data for my app, but I am having trouble creating the Model class for the API. Here is the JSON data for the for first result displayed in the data:
{
"kind": "books#volumes",
"totalItems": 1591,
"items": [
{
"kind": "books#volume",
"id": "An4_e3Cr3zAC",
"etag": "DWmqBRkB8dw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
"volumeInfo": {
"title": "The Rules of the Game",
"authors": [
"Neil Strauss"
],
"publisher": "Canongate Books",
"publishedDate": "2011-09-29",
"description": "If you want to play The Game you need to know The Rules This book is not a story. It is a how-to book. This Stylelife Challenge is not meant to be read. It is meant to be performed. Whatever experience level you have, whatever strengths and weaknesses you may have, whether you're a virgin or a Don Juan, the stage has been set for you to perform at your highest capacity. The Stylelife Challenge is a simple, easy-to-follow guide to the basics of approaching and attracting women. The Challenge is simply what works best and fastest. Neil Strauss spent four years gathering this knowledge, living it and sharing it. He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques. The result: A month-long workout program for your social, attraction, dating and seduction skills.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781847673558"
},
{
"type": "ISBN_10",
"identifier": "1847673554"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 352,
"printType": "BOOK",
"categories": [
"Biography & Autobiography"
],
"averageRating": 3.5,
"ratingsCount": 82,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.7.6.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
},
"saleInfo": {
"country": "IN",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 399.0,
"currencyCode": "INR"
},
"retailPrice": {
"amount": 279.3,
"currencyCode": "INR"
},
"buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 3.99E8,
"currencyCode": "INR"
},
"retailPrice": {
"amountInMicros": 2.793E8,
"currencyCode": "INR"
}
}
]
},
"accessInfo": {
"country": "IN",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-epub.acsm?id=An4_e3Cr3zAC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques."
}
}
]
}
I created four Model classes (as I saw fit). Here is the code of all four classes. All the classes contains their respective setters and getters.
public class BookItems {
String kind;
String id;
String etag;
String selfLink;
}
public class BookVolumeInfo {
String title;
String publisher;
String publishedDate;
String description;
long pageCount;
float averageRating;
long ratingsCount;
String maturityRating;
}
public class BookAuthors {
String authors;
}
public class BookCategories {
String categories;
}
I want to do this all in one class if possible. And when I ran the code I am not getting the title of the book. Here is the Main code of my project.
public class MainActivity extends AppCompatActivity {
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
public static final String MyAPIKey = "Your_Api_Key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);
searchButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
// Log.e(Logcat,"URL created successfully");
// Log.i(Logcat,"URL created successfully");
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
// Log.e(Logcat,"Search field empty");
// Log.i(Logcat,"Search field empty");
}
new JSONTask().execute(urlstring);
//Toast.makeText(MainActivity.this, "Search Button Clicked.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
public class JSONTask extends AsyncTask<String, String, List<BookVolumeInfo>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BookVolumeInfo> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
// URL url = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<BookVolumeInfo> bookVolumeInfoList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
BookVolumeInfo bookVolumeInfo = new BookVolumeInfo();
BookAuthors bookAuthors = new BookAuthors();
BookCategories bookCategories = new BookCategories();
bookVolumeInfo.setTitle(finalObject.getString("title"));
bookVolumeInfo.setDescription(finalObject.getString("description"));
bookVolumeInfo.setAverageRating((float) finalObject.getDouble("averageRating"));
bookAuthors.setAuthors(finalObject.getString("authors"));
bookCategories.setCategories(finalObject.getString("categories"));
bookVolumeInfoList.add(bookVolumeInfo);
}
return bookVolumeInfoList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<BookVolumeInfo> result) {
super.onPostExecute(result);
textViewDisplayResult.setText((CharSequence) result);
}
}
}
When I am running the code it is not giving any errors but when I am searching for the book it says in the Android Monitor window, "title cannot be found".
Please help.
Generate Model Class from here
Here is the full implementation of your json body to a java class
public class DemoClass {
private Items[] items;
private String totalItems;
private String kind;
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getTotalItems ()
{
return totalItems;
}
public void setTotalItems (String totalItems)
{
this.totalItems = totalItems;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private VolumeInfo volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public VolumeInfo getVolumeInfo ()
{
return volumeInfo;
}
public void setVolumeInfo (VolumeInfo volumeInfo)
{
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class SearchInfo
{
private String textSnippet;
public String getTextSnippet ()
{
return textSnippet;
}
public void setTextSnippet (String textSnippet)
{
this.textSnippet = textSnippet;
}
}
public class AccessInfo
{
private String webReaderLink;
private String textToSpeechPermission;
private String publicDomain;
private String viewability;
private String accessViewStatus;
private Pdf pdf;
private Epub epub;
private String embeddable;
private String quoteSharingAllowed;
private String country;
public String getWebReaderLink ()
{
return webReaderLink;
}
public void setWebReaderLink (String webReaderLink)
{
this.webReaderLink = webReaderLink;
}
public String getTextToSpeechPermission ()
{
return textToSpeechPermission;
}
public void setTextToSpeechPermission (String textToSpeechPermission)
{
this.textToSpeechPermission = textToSpeechPermission;
}
public String getPublicDomain ()
{
return publicDomain;
}
public void setPublicDomain (String publicDomain)
{
this.publicDomain = publicDomain;
}
public String getViewability ()
{
return viewability;
}
public void setViewability (String viewability)
{
this.viewability = viewability;
}
public String getAccessViewStatus ()
{
return accessViewStatus;
}
public void setAccessViewStatus (String accessViewStatus)
{
this.accessViewStatus = accessViewStatus;
}
public Pdf getPdf ()
{
return pdf;
}
public void setPdf (Pdf pdf)
{
this.pdf = pdf;
}
public Epub getEpub ()
{
return epub;
}
public void setEpub (Epub epub)
{
this.epub = epub;
}
public String getEmbeddable ()
{
return embeddable;
}
public void setEmbeddable (String embeddable)
{
this.embeddable = embeddable;
}
public String getQuoteSharingAllowed ()
{
return quoteSharingAllowed;
}
public void setQuoteSharingAllowed (String quoteSharingAllowed)
{
this.quoteSharingAllowed = quoteSharingAllowed;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Pdf
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
public class Epub
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
}
public class SaleInfo
{
private RetailPrice retailPrice;
private String saleability;
private ListPrice listPrice;
private Offers[] offers;
private String buyLink;
private String isEbook;
private String country;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public String getSaleability ()
{
return saleability;
}
public void setSaleability (String saleability)
{
this.saleability = saleability;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public Offers[] getOffers ()
{
return offers;
}
public void setOffers (Offers[] offers)
{
this.offers = offers;
}
public String getBuyLink ()
{
return buyLink;
}
public void setBuyLink (String buyLink)
{
this.buyLink = buyLink;
}
public String getIsEbook ()
{
return isEbook;
}
public void setIsEbook (String isEbook)
{
this.isEbook = isEbook;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Offers
{
private RetailPrice retailPrice;
private ListPrice listPrice;
private String finskyOfferType;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public String getFinskyOfferType ()
{
return finskyOfferType;
}
public void setFinskyOfferType (String finskyOfferType)
{
this.finskyOfferType = finskyOfferType;
}
}
public class RetailPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
public class ListPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
}
public class VolumeInfo
{
private String pageCount;
private String averageRating;
private ReadingModes readingModes;
private String infoLink;
private String printType;
private String allowAnonLogging;
private String publisher;
private String[] authors;
private String canonicalVolumeLink;
private String title;
private String previewLink;
private String description;
private String ratingsCount;
private ImageLinks imageLinks;
private String contentVersion;
private String[] categories;
private String language;
private String publishedDate;
private IndustryIdentifiers[] industryIdentifiers;
private String maturityRating;
public String getPageCount ()
{
return pageCount;
}
public void setPageCount (String pageCount)
{
this.pageCount = pageCount;
}
public String getAverageRating ()
{
return averageRating;
}
public void setAverageRating (String averageRating)
{
this.averageRating = averageRating;
}
public ReadingModes getReadingModes ()
{
return readingModes;
}
public void setReadingModes (ReadingModes readingModes)
{
this.readingModes = readingModes;
}
public String getInfoLink ()
{
return infoLink;
}
public void setInfoLink (String infoLink)
{
this.infoLink = infoLink;
}
public String getPrintType ()
{
return printType;
}
public void setPrintType (String printType)
{
this.printType = printType;
}
public String getAllowAnonLogging ()
{
return allowAnonLogging;
}
public void setAllowAnonLogging (String allowAnonLogging)
{
this.allowAnonLogging = allowAnonLogging;
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public String[] getAuthors ()
{
return authors;
}
public void setAuthors (String[] authors)
{
this.authors = authors;
}
public String getCanonicalVolumeLink ()
{
return canonicalVolumeLink;
}
public void setCanonicalVolumeLink (String canonicalVolumeLink)
{
this.canonicalVolumeLink = canonicalVolumeLink;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getPreviewLink ()
{
return previewLink;
}
public void setPreviewLink (String previewLink)
{
this.previewLink = previewLink;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRatingsCount ()
{
return ratingsCount;
}
public void setRatingsCount (String ratingsCount)
{
this.ratingsCount = ratingsCount;
}
public ImageLinks getImageLinks ()
{
return imageLinks;
}
public void setImageLinks (ImageLinks imageLinks)
{
this.imageLinks = imageLinks;
}
public String getContentVersion ()
{
return contentVersion;
}
public void setContentVersion (String contentVersion)
{
this.contentVersion = contentVersion;
}
public String[] getCategories ()
{
return categories;
}
public void setCategories (String[] categories)
{
this.categories = categories;
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getPublishedDate ()
{
return publishedDate;
}
public void setPublishedDate (String publishedDate)
{
this.publishedDate = publishedDate;
}
public IndustryIdentifiers[] getIndustryIdentifiers ()
{
return industryIdentifiers;
}
public void setIndustryIdentifiers (IndustryIdentifiers[] industryIdentifiers)
{
this.industryIdentifiers = industryIdentifiers;
}
public String getMaturityRating ()
{
return maturityRating;
}
public void setMaturityRating (String maturityRating)
{
this.maturityRating = maturityRating;
}
public class ImageLinks
{
private String thumbnail;
private String smallThumbnail;
public String getThumbnail ()
{
return thumbnail;
}
public void setThumbnail (String thumbnail)
{
this.thumbnail = thumbnail;
}
public String getSmallThumbnail ()
{
return smallThumbnail;
}
public void setSmallThumbnail (String smallThumbnail)
{
this.smallThumbnail = smallThumbnail;
}
}
public class ReadingModes
{
private String text;
private String image;
public String getText ()
{
return text;
}
public void setText (String text)
{
this.text = text;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
public class IndustryIdentifiers
{
private String type;
private String identifier;
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getIdentifier ()
{
return identifier;
}
public void setIdentifier (String identifier)
{
this.identifier = identifier;
}
}
}
}
}
More over you can also use Gson(https://github.com/google/gson) to convert json string directly into java pojo objects like,
new Gson().fromJson(finalJson,GoogleBook.class);

Categories

Resources