Having trouble finding the right JSON path for android project - java

JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
for (int i =0;i<resultArray.length();i++){
String sectionName = resultArray.getString("sectionName");}
I want to get the section name for this url:
https://content.guardianapis.com/search?api-key=e11b8d10-d6ef-4fb7-9c12-094c58d37687

You can get Json Value Like this.
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = null;
try {
responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
int size = resultArray.length();
for (int i =0;i<size;i++){
JSONObject myJson = resultArray.getJSONObject(i);
String sectionName = myJson.getString("sectionName");
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to convert jsonstring to jsonobject in android?

i tried to convert jsonstring to json object. but its convert only first element.
here is my code
String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}]
JSONObject j = new JSONObject(d);
its give following output
{"name":"kd","isMe":"yes","time":"10:12 AM"}
how can i convert this string into JSNOObject?
You can try like this, and your root is Json array not jsonobject
try {
JSONArray jsonArray = new JSONArray(d);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String name = jsonObject.optString("name");
String isMe = jsonObject.optString("isMe");
String time = jsonObject.optString("time");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Use this
JSONObject jsonObject = new JSONObject(my_json_string);
JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string");

Parsing another JSON Format

So here's the following code :
jObj = new JSONObject(valeurARenvoyer);
hauteur = jObj.getString("niveauEau");
debit = jObj.getString("debit");
date = jObj.getString("dateReleve");
batterie = jObj.getString("chargeBatterie");
presence = jObj.getString("etatPerimetrique");
bat = jObj.getString("chargeBatterie");
So i used this code to parse a JSON which was like that :
{"id":"15","id_Station":"Artiguelouve","Date_Releve":"2017-02-16 16:07:41","Niveau_Eau":"29","Charge_Batterie":"9","Etat_Perimetrique":"0","Debit":"13.35"}
It worked well, but now my JSON response looks like that :
{"Station":"Artiguelouve","debit":[{"niveauEau":0,"debit":32.5,"dateReleve":{"date":"2017-06-08 15:59:03","timezone_type":3,"timezone":"Europe\/Paris"},"idStation":"Artiguelouve","etatPerimetrique":true,"chargeBatterie":14590}]}
With this response i can't find how to parse this.
valeurARenvoyer is my JSON. Can you have any solution to do that please ?
add this code to get response
JSONObject jsonObject = new JSONObject(jsonResponse);//put your json response
JSONArray jsonArray = null;
try {
String station = jsonObject.getString("Station");
jsonArray = jsonObject.getJSONArray("debit");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
int niveauEau = jsonObject1.getInt("niveauEau");
int debit = jsonObject1.getInt("debit");
String isStation = jsonObject1.getString("idStation");
boolean etatPerimetrique = jsonObject1.getBoolean("etatPerimetrique");
int chargeBatterie = jsonObject1.getInt("chargeBatterie");
JSONObject jsonObject2 = jsonObject1.getJSONObject("dateReleve");
String date = jsonObject2.getString("date");
int timezone_type = jsonObject2.getInt("timezone_type");
String timezone = jsonObject2.getString("timezone");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this code
try {
JSONObject jsonObject = new JSONObject(valeurARenvoyer);
JSONArray jsonArray = jsonObject.getJSONArray("debit");
for(int i = 0; i < jsonArray.length(); i++){
// you can get niveauEau, debit, idStation, etatPerimetrique,
// chargeBatterie, dateReleve JsonObject values in this loop
}
} catch (JSONException e) {
e.printStackTrace();
}

Android JSON access thumbnail element

I have this json result http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=25&q=http://www.abc.net.au/news/feed/51120/rss.xml
I am trying to access the thumbnails for each news article located in entries>mediaGroups>contents>thumbnails>url
However I am unsure of how to access that deep in the element. This is my code so far.
public List<NewsObj> constructJSON(String jsonIN){
ArrayList<NewsObj> newsList = new ArrayList<>();
try{
//add more levels to extract json
JSONObject jsonObject1 = new JSONObject(jsonIN);
String responseData = jsonObject1.getString("responseData");
Log.d("RECEIVEJSONOBJECTLEVEL1",responseData);
JSONObject jsonObject2 = new JSONObject(responseData);
String feed = jsonObject2.getString("feed");
Log.d("RECEIVEJSONOBJECTLEVEL2",feed);
JSONObject jsonObject3 = new JSONObject(feed);
String entries = jsonObject3.getString("entries");
Log.d("RECEIVEJSONOBJECTLEVEL3", entries);
JSONArray jsonArray1 = new JSONArray(entries);
for(int i=0; i<jsonArray1.length();i++){
JSONObject mediaGroups = jsonArray1.getJSONObject(i);
String mediaItems = mediaGroups.getString("mediaGroups");
String title = mediaGroups.getString("title");
String url = mediaGroups.getString("link");
String description = mediaGroups.getString("contentSnippet");
String publishedDate = mediaGroups.getString("publishedDate");
// main information for news article
//for further thumbnail sizes?
JSONArray jsonArray2 = new JSONArray(mediaItems);
for(int j=0;j<jsonArray2.length();j++){
JSONObject contents = jsonArray2.getJSONObject(j);
String contentItems = contents.getString("contents");
Log.d("RECEIVEJSONOBJECTARRAY2",contentItems);
JSONArray jsonArray3 = new JSONArray(contentItems);
for(int k=0;k<jsonArray3.length();k++){
JSONObject items = jsonArray3.getJSONObject(k);
//too specific
String imgurl = items.getString("url");
//Log.d("RECEIVEJSONOBJECTARRAY3",imgurl);
NewsObj aObj = new NewsObj(title, imgurl,url, publishedDate);
newsList.add(aObj);
}
}
}
}catch (JSONException e){
e.printStackTrace();
Log.d("RECEIVEJSONERROR",e.toString());
}
return newsList;
}
You just need to make another JSONArray for thumbnails. For Reference See Example
Try This
public List<NewsObj> constructJSON(String jsonIN){
ArrayList<NewsObj> newsList = new ArrayList<>();
try{
//add more levels to extract json
JSONObject jsonObject1 = new JSONObject(jsonIN);
String responseData = jsonObject1.getString("responseData");
Log.d("RECEIVEJSONOBJECTLEVEL1",responseData);
JSONObject jsonObject2 = new JSONObject(responseData);
String feed = jsonObject2.getString("feed");
Log.d("RECEIVEJSONOBJECTLEVEL2",feed);
JSONObject jsonObject3 = new JSONObject(feed);
String entries = jsonObject3.getString("entries");
Log.d("RECEIVEJSONOBJECTLEVEL3", entries);
JSONArray jsonArray1 = new JSONArray(entries);
for(int i=0; i<jsonArray1.length();i++){
JSONObject mediaGroups = jsonArray1.getJSONObject(i);
String mediaItems = mediaGroups.getString("mediaGroups");
String title = mediaGroups.getString("title");
String url = mediaGroups.getString("link");
String description = mediaGroups.getString("contentSnippet");
String publishedDate = mediaGroups.getString("publishedDate");
// main information for news article
//for further thumbnail sizes?
JSONArray jsonArray2 = new JSONArray(mediaItems);
for(int j=0;j<jsonArray2.length();j++){
JSONObject contents = jsonArray2.getJSONObject(j);
String contentItems = contents.getString("contents");
Log.d("RECEIVEJSONOBJECTARRAY2",contentItems);
JSONArray jsonArray3 = new JSONArray(contentItems);
for(int k=0;k<jsonArray3.length();k++){
JSONObject items = jsonArray3.getJSONObject(k);
//too specific
String imgurl = items.getString("url");
//Log.d("RECEIVEJSONOBJECTARRAY3",imgurl);
String thumbnails = items.getString("thumbnails");
JSONArray jsonArray4 = new JSONArray(thumbnails);
for(int l=0;l<jsonArray4.length();l++){
JSONObject thumbnails1 = jsonArray4.getJSONObject(l);
String height = items.getString("height");
String width = items.getString("width");
String thumburl = items.getString("url");
}
NewsObj aObj = new NewsObj(title, imgurl,url, publishedDate);
newsList.add(aObj);
}
}
}
}catch (JSONException e){
e.printStackTrace();
Log.d("RECEIVEJSONERROR",e.toString());
}
return newsList;
}

Trying to parse JSON in Android

How would you suggest me to parse this JSON:
{"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
I need to get "username",but i cant find the way to do it. Maybe i should change JSON to something like that:
[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
This way i tried to get "user_name"s:
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONObject json = new JSONObject(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But then i get Problem with that line:
JSONObject actor = json.getJSONObject(i);
Android studio tells me that JSONObject cannot be applied to int(i). I have no idea why it doesn't work.
Can somebody please give me some hint, tutorial or an example?
Much appreciated !
The method JSONObject.getJSONObject requires a String argument (the name or key of the object), not an int. In your case, the keys are "17", "18" and "19". To get all keys, use the JSONObject.keys() method:
JSONObject json = new JSONObject(str);
Iterator<String> keyIterator = json.keys();
while (keyIterator.hasNext()) {
JSONObject actor = json.getJSONObject(keyIterator.next());
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Android studio tells me that JSONObject cannot be applied to int(i)
Because JSONObject.getJSONObject method takes key name as String instead of int. and keys in posted json is 17,18,... to access inner JSONObject.
To get all user_name from JSONObject,need to get all keys:
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject actor = json.getJSONObject(key);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Change your code like this
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONOArray jsonArray = new JSONOArray(str);
for ( int i = 0; i < jsonArray .length() ; i++)
{
JSONObject actor = jsonArray.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if you use the Gson library it's very easy.
String json = "{\"17\": {\"user_name\": \"test1\"}, \"18\": {\"user_name\": \"test5\"}, \"19\": {\"user_name\": \"test9\"}}";
Gson gson = new GsonBuilder().create();
Map<String,User> users = gson.fromJson(json, new TypeToken<Map<String,User> >(){}.getType());
for(String key : users.keySet()) {
Log.d("DEBUG",key+" -> "+users.get(key).getUser_name());
}
The User class is a simple POJO like:
public class User {
private String user_name;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
str = {"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
JSONObject ob1 = new JSONObject(str)
JSONObject ob2 = ob1.getJSONObject("17");
String userName = ob2.getString("user_name");
str = [{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
List<String> allNames = new ArrayList<String>();
JSONArray jsonArray = new JSONArray("str");
for(i=0; i < jsonArray.length(); i++){
JSONObject ob = jsonArray.getJSONObject(i);
allNames.add(ob.getString("user_name")
}
you are trying to parse JSONArray into JSONObject at
JSONObject json = new JSONObject(str);
use the below code.....
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONArray json = new JSONArray(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block`enter code here`
e.printStackTrace();
}

Convert JSONObject to List<JSONObject> or a String to List<JSONObject>

I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject objects. I can convert the string to a JSONObject using JSONObject jsonResponse = new JSONObject(responseString).
Is there any method by which I can get this in the form of a List<JSONObject>?
Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question:
https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
This method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

Categories

Resources