Response from Retrofit can't get object value - java

{ "StatusCode": 200, "StatusDescription": "OK", "ErrorMessage":
"", "ErrorDetail": "", "Results": [
{
"Key": "AccessTokens",
"Value": "[{\"Key\":\"XXXXX",
\"Value\":\"BABABA\"},{\"Key\":\"DIDADIDA\",\"Value\":\"YYYYY"
} ]"}]}
This is the response i will get when i success call the API. The datatype of "Results" is List. Can anyone explain for me how to get the "Key" and the "Value".
My Object Classes
public class KeyValueItem {
private String Key;
private String Value;
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
Response Class
public class RestServiceResponse {
#SerializedName("StatusCode")
#Expose
public int StatusCode;
public int getStatusCode() {
return StatusCode;
}
#SerializedName("StatusDescription")
#Expose
public String StatusDescription;
public String getStatusDescription() {
return StatusDescription;
}
#SerializedName("ErrorMessage")
#Expose
public String ErrorMessage;
public String getErrorMessage() {
return ErrorMessage;
}
#SerializedName("ErrorDetail")
#Expose
public String ErrorDetail;
public String getErrorDetail() {
return ErrorDetail;
}
#SerializedName("Results")
#Expose
public List<KeyValueItem> Results;
public List<KeyValueItem> getResults() {
return Results;
}
}
Anyone help please =(
Some of my code:
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
JSONArray jsonArray = new JSONArray(list);
try {
JSONObject job = jsonArray.getJSONObject(1);
String testttt = job.getString("Key");
Log.i("dsadsadsadas", testttt);
} catch (JSONException e) {
e.printStackTrace();
}
}

2 things you have to understand first.
Your JSON data is not in valid format. It contains \ (slashes) to escape double quotes in key-value pair. To confirm whether the returned JSON data is valid or not please copy & paste your JSON response into JSON validator and Formatter. Maybe problem in server script.
If you're using GsonConvertorFactory with Retrofit, Retrofit will automatically converts JSON response data to POJO internally. So, you don't need parse it again inside onResponse() method. If you get proper JSON response from server side then use it like below.
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
// code....
RestServiceResponse restServiceResponse = response.body();
if (restServiceResponse.getStatusCode() == 200) {
List<KeyValueItem> list = response.body().getResults();
for(int i = 0; i < list.size(); i++) {
KeyValueItem kvi = list.get(i);
// do whatever you want with kvi object
}
}
}

public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
for(KeyValueItem keyValueItem : list) {
String key = keyValueItem.getKey();
String value = keyValueItem.getValue();
Log.i("Keykeykey", key);
}
try {
JSONArray jsonArray = new JSONArray(value);
for(int i = 0; i < jsonArray.length();i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String keykey = obj.getString("Key");
String VAlll = obj.getString("Value");
Log.i("c1111",keykey);
Log.i("c222222", VAlll);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(restServiceResponse.getErrorMessage() != null){
builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Error");
builder.setMessage(restServiceResponse.getErrorMessage());
builder.setPositiveButton("Ok",null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
OK. Btw. i have try this to get my result. and it works!
To answer those about a invalid JSON format maybe because i have changed the value of the JSON so may have some mistake on it.
Below is the final log i get:
74/com.appandus.user.konnect I/Keykeykey: AccessTokens 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: XXXXX 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c222222: BABABA
07-12 17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: NS/NH
: DIDAIDA 07-12 17:14:38.177 6274-6274/com.appandus.user.konnect
I/c222222: YYYYYY

Related

How to parse complex data from Json via volley library in android studio?

I want to fetch data from api through volley library.
I am retrieving a JSON Object And Json Arrray via the Volley class in Android .I know how to get request but I am really struggling to parse this giant nested json .
I want to get synonyms And antonyms From the list
I want to get data from Synonmys Array and antonyms array....... Here is the link to api . Link
or Image Of Json Api - enter image description here
My Main Activity
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
// creating a new json object and
// getting each object from our json array.
try {
// we are getting each json object.
JSONObject responseObj = response.getJSONObject(i);
String word = responseObj.getString("word");
String phonetic = responseObj.getString("phonetic");
JSONArray jsonArray = responseObj.getJSONArray("meaning");
for (int k = 0; k < response.length(); k++) {
?? what to do here ????????
------------------------need help here-------------------------------
}
synonymsList.add(new synonymsModel(word,phonetic, synonyms,antonyms));
buildRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
queue.add(jsonArrayRequest);
}
Model class
public class synonymsModel {
String word, phonetic , antonyms, synonyms;
public synonymsModel(String word, String phonetic, String antonyms, String synonyms) {
this.word = word;
this.phonetic = phonetic;
this.antonyms = antonyms;
this.synonyms = synonyms;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getAntonyms() {
return antonyms;
}
public void setAntonyms(String antonyms) {
this.antonyms = antonyms;
}
public String getSynonyms() {
return synonyms;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
}

Fetching timings info from json using Retrofit

I have some problem fetching info from JSON. I'm confused about whether to use ArrayList or any other data type to retrieve data from JSON server.
I've tried to fetch data using
ArrayList<String>
in model.
Below is data format of JSON
[
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
},
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
}
]
I want to fetch all sun_timing data and mon_timing data.
That is sun_from,sun_to and mon_from,mon_to data.
Your Plain Old Java Object(POJO) for your json looks like this:
public class Example {
#SerializedName("sun_timing")
#Expose
private String sunTiming;
#SerializedName("mon_timing")
#Expose
private String monTiming;
public String getSunTiming() {
return sunTiming;
}
public void setSunTiming(String sunTiming) {
this.sunTiming = sunTiming;
}
public String getMonTiming() {
return monTiming;
}
public void setMonTiming(String monTiming) {
this.monTiming = monTiming;
}
}
See also: https://stackoverflow.com/a/40973753/10452701 for more details about How to get json via Rerofit2.
try this out working for me
private List<String> getSunList() {
ArrayList sunList = new ArrayList<String>()
String sun_json = your_json_string
try {
JSONObject jsonObject = new JSONObject(sun_json)
Log.d(TAG, "jsonObject: "+jsonObject)
Log.d(TAG, "jsonObject: "+sun_json)
JSONArray jsonArray = jsonObject.getJSONArray("sun_timing")
for (i in 0 until jsonArray.length())
{
JSONObject obj = jsonArray.get(i) as JSONObject
String sun_from = obj.getString("sun_from")
String sun_to = obj.getString("sun_to")
sunList.add(sun_from)
Log.d(TAG, "obj= "+obj)
}
}
catch (e: java.lang.Exception)
{
}
return sunList
}

Failed to show the output from json object

I want to parse json from json object and put it on textview. I tried some method but failed. The error:
expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
API SERVICE: Full ver http://139.255.86.189:83/service/api/checklistpertanyaan/1
{
"success": true,
"data": [
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
},
Harian.java
public class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
MainActivity.java
public class HarianActivity extends AppCompatActivity {
private TextView textViewResult;
/*private static String url = "http://139.255.86.189:83/service/api/checklistpertanyaan/1";*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harian);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.255.86.189:83/service/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HarianApi harianApi = retrofit.create(HarianApi.class);
Call<List<Harian>> call = harianApi.getHarian();
call.enqueue(new Callback<List<Harian>>() {
#Override
public void onResponse(Call<List<Harian>> call, Response<List<Harian>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("CodeL " + response.code());
return;
}
List<Harian> harians = response.body();
for (Harian harian : harians) {
String content = "";
content += "ID " + harian.getIdRchecklistpompa() + "\n";
content += "NAMA " + harian.getNmChecklist() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Harian>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
I would expect JSON that encapsulated a List of Harians to look like this:
[
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
}
]
Instead, yours begins with:
{
"success": true,
"data": [
...
So it isn't correct for your API to return List<Harian>. Instead, your API should return a different class which looks more like:
public class Container {
#SerializedName("success")
private boolean success;
#SerializedName("data")
List<Harian> data;
public static class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
}
And have your Retrofit API return Container rather than List<Harian>
Not sure if I understand but, to debug the problem what I would do is:
1.- Check as a String that response is a well formed JSON String.
Log.d(TAG, "My JSON String: " + response.code());
1.5.- Check if that string is a JSONObject or a JSONArray
2.- Probably try to create a JSONObject/JSONArray from that String to see if it triggers an exception.
try {
JSONObject jsonObject = new JSONObject(response.code());
} catch (JSONException e) {
e.printStackTrace();
}
3.- Try to parse the JSONObject but checking for exceptions:
try {
String nmChecklist = jsonObject.getString("nmChecklist");
} catch (JSONException e) {
e.printStackTrace();
}
4.- If you want to avoid exceptions since some objects may or may not have a key or value:
String nmChecklist = jsonObject.has("nmChecklist") && !jsonObject.isNull("nmChecklist") ? jsonObject.getString("nmChecklist") : null;
I hope this helps.
I think there is some problem with your class. The response is different from your pojo class. See json to pojo and create your Model as per the generated pojo.

How to extract the url of an image from a JSON (LastFM API)

I am a beginner in the use of JSON.
So I try to extract the url of an image from a JSON reply.
Here is the code that allows me to get an Array:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
//String url ="http://www.google.com";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search&album="+albumName+"&api_key=c51f8eb36bad&format=json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
//mTextView.setText("Response is: "+ response.substring(0,500));
Log.i("RESPONSE","Response is: "+ response);
JSONObject jsono = new JSONObject();
try {
jsono = new JSONObject(response);
//String url = jsono.getString("results");
//Log.i("RESPONSE",url);
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
try {
jsonArray = jsono.getJSONObject("results").getJSONObject("albummatches").getJSONArray("album");
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
try {
object = jsonArray.getJSONObject(i);
Log.i("RESPONSE",object.getString("image"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("RESPONSE","That didn't work!");
}
});
queue.add(stringRequest);
And here is the structure of this part in the JSON answer:
{
"album": [
{
"name": "DD Y Ponle Play",
"artist": "Jumbo",
"id": "2528039",
"url": "http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play",
"image": [
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "small"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "medium"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "large"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "extralarge"
}
]
}
]
}
How to get the url of an image for a given size?
Thank you very much for your suggestions.
You can use google GSON for this. Import it as a dependency
First create an album class.
public class Albums {
private List<Album> album;
public List<Album> getAlbum() {
return album;
}
public class Album{
private String name;
private String artist;
private String id;
private String url;
public String getName() {
return name;
}
public String getArtist() {
return artist;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public List<Image> getImage() {
return image;
}
public class Image {
#SerializedName("#text")
private String text;
private String size;
public String getText() {
return text;
}
public String getSize() {
return size;
}
}
private List<Image> image;
}
}
Now in your code where you get the above JSON object try this code below
Gson gson = new Gson();
// Im assuming "response" as the above JSON object
Albums albums = gson.fromJson(response.optString("album"),Albums.class);
This will map your json to java object.(Note: You can remove unwanted objects from the POJO as you like)
You can get the image using the getter functions
JSON is nothing but a key-value representation. It's not hard to get a hang of it. Your code should be something like this,
Update: This will only print URL's which have size = medium
String response = "{\"album\":[{\"name\":\"DD Y Ponle Play\",\"artist\":\"Jumbo\",\"id\":\"2528039\",\"url\":\"http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play\",\"image\":[{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"small\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"medium\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"large\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"extralarge\"}]}]}";
JSONObject myObject = new JSONObject(response);
JSONArray myArray = myObject.getJSONArray( "album" );
for(int i=0; i<myArray.length(); i++)
{
JSONObject myIterator = myArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
if(myInnerIterator.has( "size" ))//check if 'size' key is present
if(myInnerIterator.getString( "size" ).equalsIgnoreCase( "medium" ))
System.out.println( myInnerIterator.getString( "#text" ) );
}
}
As mentioned by Raghunandan, you're extracting a JSONObject, when you need to be extracting a JSONArray, and then from that array, you can extract a JSONObject.
Try using a library such as GSON to make this task easier, or refer to this tiny JSON library I wrote.
It's pretty simple actually to parse a JSON array:
JSONArray jsonarray = new JSONArray("album");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String url = jsonobject.getString("url");
}
Hope it helps!!!
To find the url of the images "medium" I did like this:
ArrayList<String> listUrl = new ArrayList<String>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject myIterator = null;
try {
myIterator = jsonArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
String s = myInnerIterator.getString( "size" )+myInnerIterator.getString("#text");
if (s.contains("medium") && s.contains("https")){
listUrl.add (s.replace("medium",""));
Log.i("RESPONSE",s.replace("medium",""));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I think there must be much better ... but it does the job!

How to get value of jsonObject value in android?

I am building an android application and I am new to json. I am fetching below josn formate -
{
"contact"[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
I am using below code to fetch key1 value. Now problem I am facing is how to fetch key3 value -
jsonString = http.makeServiceCall(url, ServiceHandler.GET, null);
if (jsonString != null) {
try {
JSONObject jsonObj = new JSONObject(jsonString);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me
If you want to use Gson to parse your json data. Let try it:
First of all, you must modify your json like this:
{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
Second add Gson to your libs and sync build.gradle: download here extract it, and copy/past gson-2.2.4.gson to libs folder.
Third Create some class:
FullContents.java:
public class FullContents {
private List<ObjectKey> contact;
public List<ObjectKey> getContact() {
return contact;
}
public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}
ObjectKey.java:
public class ObjectKey {
private String key1;
private List<ObjectKey3> key2;
public List<ObjectKey3> getKey2() {
return key2;
}
public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}
public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}
ObjectKey3.java:
public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}
And Finally, get data from url:
private class ParseByGson extends AsyncTask<String,Void,FullContents> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}
you can put below code to onCreate:
ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);
Update: Explain
1st of all: your json appears to be not valid (missing ':' after "content");
After reviewing thins:
You can use the named getters to retrieve many types of results (object, int, string, etc);
JSONObject contact = jsonObj.getJSONObject("contact"); // {"key1":"hey1","key2":[{"key3":"hey2"}]}
or
String key1 = jsonObj.getString("key1"); // hey1
To retrieve key3, you should use:
JSONObject contact = jsonObj.getJSONObject("contact");
JSONObject key2 = contact.getJSONObject("key2");
String key3 = key2.getString("key3");
Adapt the following code to what you are coding
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1"));
JSONObject temp_objKey2 = temp_obj.getJSONObject("key2");
Key2Object key2Object = new Key2Object();
key2Object.add(temp_objKey2.getString("key3"));
key1Array.add(key2Object);
}

Categories

Resources