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/
I am trying to fetch data from the server and then display it into the app.
I have JSON data as,
{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}
I have my JAVA class as,
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
private void getData() {
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
JSONObject companyData = result.getJSONObject(0);
name = companyData.getString(MON_O);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(name);
}
When I am triying to log the response from the server, I could see that only the COLUMNS value is there where as the DATA is null.
Also, I am getting an error as below,
System.err: org.json.JSONException: Value TIMEID at 0 of type java.lang.String cannot be converted to JSONObject
Why would I get the DATA values from the server as null and how am I suppose to fix the error?
I have referred the links: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
However, these do not seem to help in my case. Please can anyone help?
Try this.....
JSONParser jsonParser = new JSONParser();
jsonObject = jsonParser.getJSONFromUrl(url);
try {
user1 = jsonObject.getJSONArray("COLUMNS");
for (int i = 0; i < user1.length(); i++) {
String value = (String) user1.get(i);
getList.add(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
I observe your json response, i think whatever you are having in column json array there are nothing having string which you are getting thats why you are getting error,
In your response nothing having key value pair so its easy to get String.
so you should getString() instead of getJsonObject()
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("TAG", jsonObject.toString());
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
name = result.getString(index);
Log.e(name,"datadtadattadtatadtat");
} catch (JSONException e) {
e.printStackTrace();
}
index is basically json array index you can put it 0 or something and go for loop if you want.
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");
I am trying to get the user details using people.get in which I have emails which I need to get that value.
This is what I mean:
This is how I'm trying to do but unable to get the value
try {
String resp =profile.getEmails().toString();
JSONObject mainObject = new JSONObject(resp);
JSONObject uniObject = mainObject.getJSONObject("emails");
String email = uniObject.getString("value");
((TextView) findViewById(R.id.txtemail)).setText(email);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any help is appreciated.
In your JSON response, emails is a JSONArray, not a JSONObject. You would need to get it like this:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("email");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("value");
String firstName = obj.getString("type");
EmailResponse myResp = new EmailResponse();
myResp.setValue(value);
myResp.setType(type);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class EmailResponse{
public String value = "";
public String type = "";
//getter setters
}
Hope this helps.
i have this json : {"id":1,"name":"john smith"}
How i can parse it? i know i have to do this with this function:
public static String parseJSONResponse(String jsonResponse) {
String name = "";
JSONObject json;
try {
json = new JSONObject(jsonResponse);
JSONObject result = json.getJSONObject("**********");
name = result.getString("**********");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
but i dont know what can i put in the areas incated with "****". please help me
i only want to fetch id and name values.
parse current json String as:
json = new JSONObject(jsonResponse);
// get name here
name = json.getString("name");
// get id here
id = json.getString("id");
because current json string contain only one jsonObject
use this method to parse your JSON String
public static String parseJSONResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
// get name & id here
String name = json.getString("name");
int id = json.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
For more Refer this Link