As you can see in the picture I have JSON object 'multimedia' which has information about picture in 4 different formats. I need url only on of them. Lets say which had standard format (75x75). I use volley library in my android application. I am confused about how to take/parse url (in string format is enough) of image that underlined in the picture.
Here is code that I used:
NewsFragment:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
sendJsonRequest();
}
private void sendJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(10),
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONRequest(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private void parseJSONRequest(JSONObject response){
if(response==null || response.length()==0){
return;
}
try {
JSONArray arrayResult = response.getJSONArray(Keys.EndPointNews.KEY_RESULTS);
for (int i = 0; i < arrayResult.length(); i++){
JSONObject currentResult = arrayResult.getJSONObject(i);
String section = currentResult.getString(Keys.EndPointNews.KEY_SECTION);
String subsection = currentResult.getString(Keys.EndPointNews.KEY_SUBSECTION);
String title = currentResult.getString(Keys.EndPointNews.KEY_TITLE);
String article_abstract = currentResult.getString(Keys.EndPointNews.KEY_ABSTRACT);
String published_date = currentResult.getString(Keys.EndPointNews.KEY_PUBLISHED_DATE);
// HERE IS A PROBLEM: EDIT:
JSONArray arrayMultimedia = currentResult.getJSONArray(Keys.EndPointNews.KEY_MULTIMEDIA);
JSONObject objectMultimedia = arrayMultimedia.getJSONObject(0);
String multimediaURL = null;
if(objectMultimedia.has(Keys.EndPointNews.KEY_MULTIMEDIA_URL))
{
multimediaURL = objectMultimedia.optString(Keys.EndPointNews.KEY_MULTIMEDIA_URL);
}
News news = new News();
news.setSection(section);
news.setSubsection(subsection);
news.setArticleTitle(title);
news.setArticleAbstract(article_abstract);
Date date = mDateFormat.parse(published_date);
news.setPublishedDate(date);
//EDIT
news.setMultimediaURL(multimediaURL);
mListNews.add(news);
}
Toast.makeText(getActivity(),mListNews.toString(),Toast.LENGTH_LONG).show();
}catch (JSONException e){
}
catch (ParseException e) {
e.printStackTrace();
}
}
THANKS FOR ANY HELP!
EDIT:
public String getMultimediaURL(){
return multimediaURL;
}
public void setMultimediaURL(String multimediaURL){
this.multimediaURL = multimediaURL;
}
I must suggest you to go with GSON library for parsing your JSON reposnses. it is very easy, you have to just create your template/entity classes. here is the link and download gson library from here
OR
refer below answer by #ρяσѕρєя K
OR
refer this answer
multimedia is JSONArray instead of JSONObject. get multimedia json array from currentResult JSONObject:
JSONObject currentResult = arrayResult.getJSONObject(i);
JSONArray arrMultimedia = currentResult.getJSONArray(
Keys.EndPointNews.KEY_MULTIMEDIA);
multimedia array contain JSONObejct so get JSONObject from arrMultimedia to get all values using key:
JSONObject jsonObjMultimedia = arrMultimedia.getJSONObject(0);
String strPicUrl=jsonObjMultimedia.optString("url");
Related
Im using Rest Countries API to retrieve language data, https://restcountries.eu/rest/v2/all.. but the languages does't show up because the data was in array.
this is the code that i write to retrieve the data using Method.Get
private void getCountriesList() {
String url = "https://restcountries.eu/rest/v2/all";
StringRequest request = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.isEmpty()) {
Gson gson = new Gson();
JSONObject json = null;
// array of country
LanguageModel[] countries = gson.fromJson(response, LanguageModel[].class);
// add it to adapter
for(LanguageModel country: countries) {
mAdapter.addItem(country);
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getLocalizedMessage());
}
}
);
Volley.newRequestQueue(getApplicationContext()).add(request);
}
This is the model. the code was successful when i retrieve country name, but it was failed when i retrieve language data
public class CountryModel {
private String languages;
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}}
I got it working with the following code:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject countryObj = mainArray.getJSONObject(i);
JSONArray languageArray = countryObj.getJSONArray("languages");
List<LanguageModel> languageModels = gson.fromJson(languageArray.toString(), new TypeToken<List<LanguageModel>>() {
}.getType());
// add it to adapter
for (LanguageModel languageModel : languageModels) {
//mAdapter.addItem(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// array of country
}
Let me know if you still get the error.
Edit:
but how to get country name and language at the same time?
You have to edit your CountryModel as following:
public class CountryModel {
#SerializedName("name")
String countryName;
#SerializedName("languages")
ArrayList<LanguageModel> languages;
public CountryModel() {
}
}
And LanguageModel as following:
class LanguageModel {
#SerializedName("iso639_1")
String iso1;
#SerializedName("iso639_2")
String iso2;
#SerializedName("name")
String name;
#SerializedName("nativeName")
String nativeName;
public LanguageModel() {
}
}
Now the final change in parsing:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
List<CountryModel> countryList = gson.fromJson(mainArray.toString(), new TypeToken<List<CountryModel>>() {
}.getType());
//do something with your country list
Log.d("R-Countries", countryList.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
While this answer works you should see the following link to understand what i did here.
http://www.studytrails.com/java/json/java-google-json-introduction/
Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?
hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"
String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first
I am trying parsing below json in android with below code but I get a error when I do parsing process,How can I parse it? When I do parsing process I get a error in this step final JSONObject jsonm_kurulum = jsonm.getJSONObject("GetkurulumByIDResult");
{
"GetkurulumByIDResult":{
"Astron_test":"OK",
"Note":null,
"aciklama":"ok",
"adres":null,
"bayiID":242,
"bayi_Adi":null,
"bayi_kodu":null,
"descripID":null,
"descriptionCode":null,
"durum":"1",
"form_no":"000008",
"gsm_no":"5493279096",
"kurulum_tarihi":"\/Date(1473022800000+0300)\/",
"muhdendis":"umut",
"ricon_sn":"9922R1608HH0800087",
"signal":"17",
"sira_no":124,
"yetki":"Gökhan Karolo"
}
}
final JSONObject jsonm = new JSONObject(result);
Log.i("#Log", "GetInfogiris");
final JSONObject jsonm_kurulum = jsonm.getJSONObject("GetkurulumByIDResult");
String jsonm_astron = jsonm_kurulum.getString("Astron_test");
String jsonm_note = jsonm_kurulum.getString("Note");
String jsonm_aciklama = jsonm_kurulum.getString("aciklama");
String jsonm_adres = jsonm_kurulum.getString("adres");
String jsonm_bayiId = jsonm_kurulum.getString("bayiID");
String jsonm_bayiAdi = jsonm_kurulum.getString("bayi_Adi");
String jsonm_kodu = jsonm_kurulum.getString("bayi_kodu");
result = {"GetkurulumByIDResult":{"Astron_test":"OK","Note":null,"aciklama":"ok","adres":null,"bayiID":242,"bayi_Adi":null,"bayi_kodu":null,"descripID":null,"descriptionCode":null,"durum":"1","form_no":"000008","gsm_no":"5493279096","kurulum_tarihi":"\/Date(1473022800000+0300)\/","muhdendis":"umut","ricon_sn":"9922R1608HH0800087","signal":"17","sira_no":124,"yetki":"Gökhan Karolo"
}
}
To share optimized way of json parsing, I would suggest you to follow below steps:
Use Gson library (you would not need to parse json response manually but instead it will give you POJO based output and so you would be accessing data using getter and setter methods)
Use this site to create POJO class from JSON http://www.jsonschema2pojo.org/
Try this:
private void parsing(String Url) {
private ServiceRequest mRequest;
mRequest = new ServiceRequest(Activity.this);
mRequest.makeServiceRequest(Url, Request.Method.POST, jsonParams, new ServiceRequest.ServiceListener() {
#Override
public void onCompleteListener(String response) {
String Sstatus = "";
try {
JSONObject jsonm_kurulum = new JSONObject(response);
String jsonm_astron = jsonm_kurulum.getString("Astron_test");
String jsonm_note = jsonm_kurulum.getString("Note");
String jsonm_aciklama = jsonm_kurulum.getString("aciklama");
String jsonm_adres = jsonm_kurulum.getString("adres");
String jsonm_bayiId = jsonm_kurulum.getString("bayiID");
String jsonm_bayiAdi = jsonm_kurulum.getString("bayi_Adi");
String jsonm_kodu = jsonm_kurulum.getString("bayi_kodu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
#Override
public void onErrorListener() {
dialog.dismiss();
}
});
}
I have an app in which i sent a server request and in response server send me a set of array and from that set of array I extract a string named as "dealname" and after that i have a textview in which i want to show this string every after 5 seconds like using Thread.sleep() and when arraycome to end i want to start from 1st array.How can I do that pls help.
here is the code i am trying
private CDealAppDatastorage item;
private String TAG = MainActivity.class.getSimpleName();
private ArrayList<CDealAppDatastorage> s_oDataset;
try{
String json;
JSONObject jsonObject = new JSONObject();
jsonObject.put("dealcategory","DEALTEST");
json = jsonObject.toString();
Log.e(TAG,"Server Reqeust::-"+json);
final String m_szTicker = "http://14.192.16.1555:8080/rest/json/metallica/getDealListsJSON?";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_szTicker,jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG,"Server Response::"+response);
try{
if (response.getString("resultdescription").equalsIgnoreCase("Transaction Successful")){
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from r
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
s_oDataset.add(item);// add all items in ArrayList
}
int i;
for (i=0;i<s_oDataset.size();i++){
Log.e(TAG,"Data Size:"+i);
final int finalI = i;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
CDealAppDatastorage m = s_oDataset.get(finalI);
m_Text.setText(m.getM_szHeaderText());
}
},6000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());// creating object of Request queue
requestQueue.add(jsonObjectRequest);// add json Object request to request queue
}catch (Exception e){
e.printStackTrace();
Change the loop logic so it will start over again if the list ends.
int i;
int size = s_oDataset.size();
for (i=0;;i++){
Log.e(TAG,"Data Size:"+i);
final int finalI = i % size; //this will loop again from start if lists ends
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
CDealAppDatastorage m = s_oDataset.get(finalI);
m_Text.setText(m.getM_szHeaderText());
}
},6000);
}