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);
}
Related
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."
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.
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");
}
I'm getting a JSON Exception in this code:
JSONObject jObject = new JSONObject(JSONString);
pontosUsuario.setIdUsuario(jObject.getInt("idUsuario"));
//Toast.makeText(this, pontosUsuario.idUsuario, Toast.LENGTH_LONG).show();
pontosUsuario.setNomeUsuario(jObject.getString("nomeUsuario"));
pontosUsuario.setCPF(jObject.getString("CPF"));
pontosUsuario.setEmail(jObject.getString("email"));
pontosUsuario.setSigla(jObject.getString("sigla"));
pontosUsuario.setSenha(jObject.getString("senha"));
pontosUsuario.setInstuicao(jObject.getString("instituicao"));
JSONArray jArr = new JSONArray(jObject.getString("listaDePontos"));
for (int i = 0; i < jArr.length(); i++) {
JSONObject temp = jArr.getJSONObject(i);
Ponto ponto = new Ponto();
ponto.setIdPonto(temp.getString("idPonto"));
ponto.setPontoNome(temp.getString("pontoNome"));
String data = temp.getString("dtCampo");
data = data.substring(0, 10);
//dtCampo = temp.getString("dtCampo");
try {
ponto.setDtCampo(new SimpleDateFormat(data, Locale.ENGLISH).parse(data));
} catch (ParseException e) {
e.printStackTrace();
}
ponto.setProjeto(temp.getInt("projeto"));
ponto.setUTMEste(temp.getDouble("UTMEste"));
ponto.setUTMNorte(temp.getDouble("UTMNorte"));
ponto.setUTMFuso(temp.getInt("UTMFuso"));
ponto.setUTMHemisferio(temp.getString("UTMHemisferio"));
ponto.setLatDec(temp.getDouble("latDec"));
ponto.setLongDec(temp.getDouble("longDec"));
ponto.setAltitude(temp.getInt("altitude"));
ponto.setDescPonto(temp.getString("descPonto"));
ponto.setComplement(temp.getString("complement"));
//ponto.getAnaliseCampo();
AnaliseCampo analiseCampo = new AnaliseCampo();
//JSONObject anObj = jObject.getJSONObject("analiseCampo");
JSONObject anObj = jObject.getJSONObject("analiseCampo");
//AnaliseCampo analiseCampo = new AnaliseCampo();
analiseCampo.setNomeEstrutura(anObj.getString("nomeEstrutura"));
analiseCampo.setIdAnCampo(anObj.getString("idAnCampo"));
analiseCampo.setDescEstrutura(anObj.getString("descEstrutura"));
analiseCampo.setEhBrunton(anObj.getBoolean("ehBrunton"));
ponto.setAnaliseCampo(analiseCampo);
//ponto.setAnaliseCampo(temp.get("analiseCampo");
The Exception is: detailMessage "No value for analiseCampo" (id=830007838576)
Here is the Ponto.class:
public class Ponto {
private String idPonto;
private String pontoNome;
private Date dtCampo;
private int projeto;
private double UTMEste;
private double UTMNorte;
private int UTMFuso;
private String UTMHemisferio;
private double latDec;
private double longDec;
private int altitude;
private String descPonto;
private String complement;
private AnaliseCampo analiseCampo;
private ArrayList<Arquivo> arquivos;
private ArrayList<PontoUnGeologica> idUnidadeGeologica;
public String getIdPonto() {
return idPonto;
}
public void setIdPonto(String idPonto) {
this.idPonto = idPonto;
}
public String getPontoNome() {
return pontoNome;
}
public void setPontoNome(String pontoNome) {
this.pontoNome = pontoNome;
}
public Date getDtCampo() {
return dtCampo;
}
public void setDtCampo(Date dtCampo) {
this.dtCampo = dtCampo;
}
public int getProjeto() {
return projeto;
}
public void setProjeto(int projeto) {
this.projeto = projeto;
}
public double getUTMEste() {
return UTMEste;
}
public void setUTMEste(double uTMEste) {
UTMEste = uTMEste;
}
public double getUTMNorte() {
return UTMNorte;
}
public void setUTMNorte(double uTMNorte) {
UTMNorte = uTMNorte;
}
public int getUTMFuso() {
return UTMFuso;
}
public void setUTMFuso(int uTMFuso) {
UTMFuso = uTMFuso;
}
public String getUTMHemisferio() {
return UTMHemisferio;
}
public void setUTMHemisferio(String utmHemisferio) {
UTMHemisferio = utmHemisferio;
}
public double getLatDec() {
return latDec;
}
public void setLatDec(double latDec) {
this.latDec = latDec;
}
public double getLongDec() {
return longDec;
}
public void setLongDec(double longDec) {
this.longDec = longDec;
}
public int getAltitude() {
return altitude;
}
public void setAltitude(int altitude) {
this.altitude = altitude;
}
public String getDescPonto() {
return descPonto;
}
public void setDescPonto(String descPonto) {
this.descPonto = descPonto;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public AnaliseCampo getAnaliseCampo() {
return analiseCampo;
}
public void setAnaliseCampo(AnaliseCampo analiseCampo) {
this.analiseCampo = analiseCampo;
}
public ArrayList<Arquivo> getArquivos() {
return arquivos;
}
public void setArquivos(ArrayList<Arquivo> arquivos) {
this.arquivos = arquivos;
}
public ArrayList<PontoUnGeologica> getIdUnigadeGeologica() {
return idUnidadeGeologica;
}
public void setIdUnigadeGeologica(ArrayList<PontoUnGeologica> idUnigadeGeologica) {
this.idUnidadeGeologica = idUnigadeGeologica;
}
public Ponto()
{
arquivos = new ArrayList<Arquivo>();
idUnidadeGeologica = new ArrayList<PontoUnGeologica>();
analiseCampo = new AnaliseCampo();
}
}
And this is the AnaliseCampo.class
public class AnaliseCampo {
public String nomeEstrutura;
public String idAnCampo;
public String descEstrutura;
public boolean ehBrunton;
public ArrayList<AnaliseEstrutural> analiseEstruturais;
public String getNomeEstrutura() {
return nomeEstrutura;
}
public void setNomeEstrutura(String nomeEstrutura) {
this.nomeEstrutura = nomeEstrutura;
}
public String getIdAnCampo() {
return idAnCampo;
}
public void setIdAnCampo(String idAnCampo) {
this.idAnCampo = idAnCampo;
}
public String getDescEstrutura() {
return descEstrutura;
}
public void setDescEstrutura(String descEstrutura) {
this.descEstrutura = descEstrutura;
}
public boolean isEhBrunton() {
return ehBrunton;
}
public void setEhBrunton(boolean ehBrunton) {
this.ehBrunton = ehBrunton;
}
public ArrayList<AnaliseEstrutural> getAnaliseEstruturais() {
return analiseEstruturais;
}
public void setAnaliseEstruturais(
ArrayList<AnaliseEstrutural> analiseEstruturais) {
this.analiseEstruturais = analiseEstruturais;
}
public AnaliseCampo()
{
analiseEstruturais = new ArrayList<AnaliseEstrutural>();
}
}
Here is the JSON:
"idUsuario": 20,
"nomeUsuario": "Barbara Trzaskos",
"CPF": "978824029-15",
"email": "barbaratrzaskos#ufpr.br",
"sigla": "BTR",
"senha": "safira",
"instuicao": "Universidade Federal do Paraná",
"listaDePontos": [
{
"idPonto": "BTR0001",
"pontoNome": "BTR-0001",
"dtCampo": "2011-04-29T00:00:00",
"projeto": 2,
"UTMEste": 547276.0,
"UTMNorte": 7285137.0,
"UTMFuso": 22,
"UTMHemisferio": "S",
"latDec": -24.5469,
"longDec": -50.5332,
"altitude": 0,
"descPonto": "Arenito mal selecionado. Apresenta fina banda de deformação, como um suave ressalto no relevo e coloração mais clara. Exibe plano subvertical com padrão anastomosado e cinemática aparente sinistral",
"complement": "Coleta de amostra orientada.",
"analiseCampo": {
"nomeEstrutura": "-",
"idAnCampo": "BTR0001",
"descEstrutura": "",
"ehBrunton": true,
"analiseEstruturais": [
{
"idEstrutura": "BTR0001001",
"ordem": 0,
"tipo": "Plano",
"codigo": "F",
"brunton": "N42W/86SW",
"clar": "228/86",
"azimute": "228",
"direcao": "42",
"quadrante": "SW",
"sentido": "Sinistral",
"descricao": "",
"mergulho": "86",
"familia": ""
}
]
},
"arquivos": [],
"idUnigadeGeologica": [
{
"idUnidade": 816
},
{
"idUnidade": 2295
}
]
}
]
You are accessing the wrong JSON object in this line:
JSONObject anObj = jObject.getJSONObject("analiseCampo");
It should be:
JSONObject anObj = temp.getJSONObject("analiseCampo");
Since temp is what you are assigning each element of the listaDePontos array to. On a side note, given the complexity of your data, you should consider mapping the JSON directly to your object using:
String json = "" ; // <-- your JSON here
Ponto ponto = new Gson().fromJson(json, Ponto.class);
I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Here you have a tutorial which answers your needs - Android + Gson