please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !
Here is a link: http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js with JSON objects. There are 261 objects with unique value (strings). How to get each object with numbers (2101, 2107 etc.) and 2 strings inside (picture and title)?
So this is my technologies AsyncTask:
ListView listView;
TechnologiesAdapter adapter;
ArrayList<Technologies> techList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
techList = new ArrayList<Technologies>();
new TechnologiesAsyncTask().execute("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
}
public class TechnologiesAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
//How to get the other objects?
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
You can get all of the names to a json array, then get every json object from the names in json array.
Following is a simple example.
private class DataAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("technology");
JSONArray nameArray = jsonObject.names();
final int size = nameArray.length();
for (int i = 0; i < size; i++) {
JSONObject object = jsonObject.getJSONObject(nameArray.getString(i));
// get id, title and pictures, etc
Log.d(TAG, nameArray.getString(i) + " " + object.getString("title") + " " + object.getString("picture"));
}
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
After you get the "technology" object just create another JSONObject from that like this:
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
// Get the 2101 object
JSONObject jObj3 = jObj2.getJSONObject("2101");
// Get the picture and title of 2101
String picture = jObj3.getString("picture");
String title = jObj3.getString("title");
Your JSON looks like it might be better suited to use a JSONArray instead of nested JSONObjects though.
JSONObject jPages=jQuery.getJSONObject("pages");
Iterator < String> keys = jPages.keys();
while(keys.hasNext()){
JSONObject jPageId=jPages.getJSONObject(keys.next());
//Action need to be performed
}
I'm new to JSON android java eclipse. I am doing a listview with images and parsing json array. I followed this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ . In that tutorial, their JSON array contains the array name.However, mine doesn't contain the array name. So my question is how to code JSON Array without the array name?
Below is my JSON code.
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
},
{
"event_id": "EV00000002",
"event_title": "Movie2",
}
]
Below is my JSON coding for parsing the JSON.
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Events event = new Events();
event.setevent_title(object.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
What am i suppose to do?
This problem is solved. Thus, i will be posting the correct code.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Events event = new Events();
event.setevent_title(obj.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
Here is a little example:
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("key", "value");
array.put(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("key2", "value2");
array.put(obj2);
That would look like:
[
{
"key": "value"
},
{
"key2": "value2"
}
]
If you want to get information about your JSONObjects in your JSONArray just iterate over them:
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
object.get("event_id");
object.get("event_title");
}
You can use GSON librery, it's very easy to use. Just create a class (model)
public class Event{
private String event_id;
private String event_title;
...
}
and in your main activity
Event ev = new Event ("EV00000001", "Movie 1")
Gson gson = new Gson();
gSon = gson.toJson(ev);
Log.i("gson", gSon);
and you will get JSON
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
}
]
What you have is an array of JSON Objects.
What the tutorial has is a JSON Object that has a property, which has an array of JSON objects.
When you look at these, here is a simple way to differentiate the two:
[] -> Array
{} -> Object
So in your code, instead of doing
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
You might want to do:
JSONArray jarray = new JSONArray(data);
First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}
I need help in parsing big Json file:
{"status":{"code":200,"text":"OK"},"content":[{"proposalId":"12536","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12537","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12538","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12539","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
................[etc]
I need to take all titles and proposalIds in content.
I tried to make it like this:
public ArrayList<String> GetUserProposals(String UserId){
String actionname = sitename+"accounts/"+UserId+"/proposals";
try {
jObject = this.sendData(actionname);//change later
// return result;
JSONArray ja = jObject.getJSONArray("content");
for (int i = 0; i < ja.length(); i++) {
Log.i("MyDebug", "value----" + ja.getJSONObject(i).getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> returnValue = null;
return returnValue;
}
But JSONArray is empty.
My JSON String was
{
"result": "success",
"countryCodeList": [
{
"countryName": "World Wide",
"countryCode": "00"
},
{
"countryName": "Korea, Republic of",
"countryCode": "kr"
},
{
"countryName": "United States",
"countryCode": "us"
},
{
"countryName": "Japan",
"countryCode": "jp"
},
{
"countryName": "China",
"countryCode": "cn"
},
{
"countryName": "India",
"countryCode": "in"
}
]
}
And I parsed this way
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
you should try switching your jObject = this.sendData(actionname); to 'jObject = new JSONObject(this.sendData(actionname));`
you have to initialize the JSON object and you aren't...
This will help you Dude..while Parsing JSON there will be json array [] and json object {}
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(
"Your Json URL");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream,
"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = sb.toString();
int k = 0;
JSONObject jObject = null;
jObject = new JSONObject(result);
String aJsonString = jObject.getString("results");
String name = aJsonString;
JSONArray jArray = null;
jArray = jObject.getJSONArray("results");
JSONObject oneObject = null;
oneObject = jArray.getJSONObject(0);
JSONArray jArray1 = null;
jArray1 = oneObject.getJSONArray("address_components");//keyword
JSONObject oneObject1 = null;
oneObject1 = jArray1.getJSONObject(1);
String oneObjectsItem1 = oneObject1.getString("long_name");//keyword
City = oneObjectsItem1;
}
catch (IOException e) {
int x = 0;
}
return City;