I have the below JSON
{"data":{
"result": true,
"applications": [
{
"application_name": "Hill Rider Game",
"application_os": "Android",
"app_downloads": "1,000,000+",
"bundle_id": "com.touchfoo.swordigo",
"playstore": {
"downloads": "1,000,000 - 5,000,000",
"rating": 4.3144540786743,
"developer": "Touch Foo",
"screenshots": [
"https://lh4.ggpht.com/B8xLNXsT_OOezuHDMtX1ZqRgEX_D8NV79bktaLpJ41Rh9Ng8dJ_vC35mEmXiT4iOrhc=h310",
"https://lh6.ggpht.com/VCWp2ltqspB2qjznCeq9hhMwdG10nxYfg2URbH1_F8cmdtkW-MLCS0aJUnZ-IvnNXg=h310",
"https://lh4.ggpht.com/DJqmDOgAqC_COJI5AVTxWeehcM6B51bFkedVRIG0iQdrxsHf42Dy0-NPDfw5nhnXDEOB=h310",
"https://lh5.ggpht.com/E0VlpwiBGTBPnCpzekxv6kJG1FCaPQENuxXi1OUu9jGv7Ib-vc4j4AkaGugz7bjhg94-=h310"
]
}
},
{
"application_name": "Appprix Testing",
"application_os": "Android",
"app_downloads": "10,000,000+",
"bundle_id": "com.creativemobile.dragracingbe",
"playstore": {
"downloads": "10,000,000 - 50,000,000",
"rating": 4.2277860641479,
"developer": "Creative Mobile",
"screenshots": [
"https://lh6.ggpht.com/mZxezzFUAyRz7g2zcULV8vLILrMs6yuP_Yux60F3DPA7x89TIlLzgWkDgyQFhugAMQc=h310",
"https://lh4.ggpht.com/iapxrJoX2u-O3wvh9i9J6L4_tmyoflj2OGbZCe8xdJiqb8EE8yIH3lzE1h0UinfqDQ=h310",
"https://lh5.ggpht.com/YgDWaxt00LBEd-5p-AfVhAxf7u45m82mD2Uk44wkQm0QBCxEMYX4rrUaWDaS9PEvTSE=h310",
"https://lh6.ggpht.com/k5ixEniw9F6sZ-B0HU2ckEHg9tBsjMz45xZ2LX3-hcjLcFTT4_VZfTBkbqVYDXnlYSQ=h310"
]
}
},
{
"application_name": "Hill Climb SteamPunk",
"application_os": "Android",
"app_downloads": "1,000,000+",
"bundle_id": "com.touchfoo.swordigo",
"playstore": {
"downloads": "1,000,000 - 5,000,000",
"rating": 4.3144540786743,
"developer": "Touch Foo",
"screenshots": [
"https://lh4.ggpht.com/B8xLNXsT_OOezuHDMtX1ZqRgEX_D8NV79bktaLpJ41Rh9Ng8dJ_vC35mEmXiT4iOrhc=h310",
"https://lh6.ggpht.com/VCWp2ltqspB2qjznCeq9hhMwdG10nxYfg2URbH1_F8cmdtkW-MLCS0aJUnZ-IvnNXg=h310",
"https://lh4.ggpht.com/DJqmDOgAqC_COJI5AVTxWeehcM6B51bFkedVRIG0iQdrxsHf42Dy0-NPDfw5nhnXDEOB=h310",
"https://lh5.ggpht.com/E0VlpwiBGTBPnCpzekxv6kJG1FCaPQENuxXi1OUu9jGv7Ib-vc4j4AkaGugz7bjhg94-=h310"
]
}
},
{
"application_name": "abcd",
"application_os": "Android",
"app_downloads": "10,000+",
"bundle_id": "com.piggypop.cricket",
"playstore": {
"downloads": "10,000 - 50,000",
"rating": 3.9359374046326,
"developer": "Piggy Pop",
"screenshots": [
"https://lh3.ggpht.com/vvpskwV3TfsrzkmLXF4_NIEY-fzKYFjiXtpF8C2ovS6mJlfYG4dkGAYsSWHbv1lzmw=h310",
"https://lh5.ggpht.com/RrfwHr3lEfaqOtg_Hoa30EMuP9cS_GW4fAeZH_W3SCcubi1IiqV5OpuyMTWT8gPbwQ=h310",
"https://lh4.ggpht.com/WdivGfxtUAKPxhMGayfLD5egCm3y0mz8RBQcyCnQBhuHAE_a5deZmAv4evkwGny6eHQ=h310",
"https://lh5.ggpht.com/sbLzAUgprB8vQkqLMgqdAz2TyI5az572scxVuPoHa8I2zk7B5euCebx3ECr4iOHLxvA=h310",
"https://lh5.ggpht.com/6Vk9DTDY4Grcn_OaiaJmEuaR2fi94H55PyEYg9NhbPAoxjRnMgt7oZBaA1SQLVfSj1w=h310"
]
}
}
]
}
}
I need to get "screenshots" tag array. This is my code
JSONArray responseArray = jsonObj.getJSONArray("body");
for (int i = 0; i < responseArray.length(); i++) {
JSONArray applicationsArray = c.getJSONArray("applications");
for (int k = 0; k < applicationsArray.length(); k++) {
JSONObject e = applicationsArray.getJSONObject(k);
JSONArray playstore = e.getJSONArray("playstore");
for (int l = 0; l < playstore.length(); l++) {
JSONObject f = playstore.getJSONObject(l);
Log.e("scren ",""+f.getString("screenshots"));
JSONArray screenshotArray = f.getJSONArray("screenshots");
Log.e("scren ",""+screenshotArray);
}
}
jsonObj contain json value
JSONObject data = jsonObj.getJSONObject("data");
JSONArray applications = data.getJSONArray("applications");
for (int k = 0; k < applications.length(); k++) {
JSONObject playstore = applications[k].getJSONObject("playstore");
JSONArray screenshots = playstore.getJSONArray("screenshots");
for (int i = 0; i < screenshots.length(); i++) {
Log.e("screenshot ",""+screenshots[i]);
}
}
you can try like this
Assuming you already have setup all the prerequisites for json parsing in android.
I will move towards how to parse this data
if(response!=null){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray jsonArray = jsonObject.optJSONArray("applications");
for(int i=0; i<jsonArray.length(); i++){
jsonObject= jsonArray.getJSONObject(i);
JSONObject c = jsonArray.getJSONObject(i);
String app_name = c.getString("application_name");
String app_os = c.getString("application_os");
String app_downloads = c.getString("app_downloads");
String bundle = c.getString("bundle_id");
// playstore node is JSON Object
JSONObject playstore = c.getJSONObject("playstore");
String downloads = phone.getString("downloads");
String rating = phone.getString("rating");
String developer = phone.getString("developer");
// screenshots node is JSON Array
JSONArray screenshots = jsonObject.optJSONArray("screenshots");
for(int j=0; j<screenshots.length(); j++){
Log.e("screenshot ",""+screenshots[i]);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I am working on an Android project, in which I am using Volley to consume an Api. The query is being done correctly and the next JSON returns to me. I am trying to access the elements of this jsonArray in java
[
{
"Estado": 1,
"_id": "5dfd27fb971f730f31cc12d5",
"empresas": "5dfbeec1f87e0e3030b38143",
"Codigo": "1001AZXL001",
"Codigo_Barras": "7702345654127",
"Descripcion": "JEAN talla XL ",
"Detalles": [
{
"_id": "5dfd27fb971f730f31cc12d7",
"bodegas": "5dfd2383971f730f31cc12cf",
"Cantidad": 6,
"Precio": 150000,
"Unidad_Medida": "UND"
},
{
"_id": "5dfd27fb971f730f31cc12d6",
"bodegas": "5dfd23b7971f730f31cc12d0",
"Cantidad": 15,
"Precio": 150000,
"Unidad_Medida": "UND"
}
],
"Talla": "XL",
"Color": "AZ",
"Minimo": 5000,
"Maximo": 30000,
"Fecha_Creacion": "2019-12-20T19:58:51.720Z"
}
]
For that I am using the following code
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
}
catch(JSONException e) {
}
}
}
But I cannot access the elements that are inside the "Detalles" object
Use the following :
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
JSONArray array = jsonObject.getJSONArray("Detalles")
for(int j = 0; j < array.length() ; ++j){
try{
JSONObject jsonObject2 = array.getJSONObject(j);
//ACCESS THE PARAMETERS OF detalles HERE FOR EX :
String bodegas = jsonObject2.getString("bodegas");
}catch(JSONException e) {}
}
}
catch(JSONException e) {
}
}
}
This is another Jsonarray, if you want to get the data inside, you Need to get the Jsonarray and read the data from there.
JSONArray array = jsonObject.getJSONArray("Detalles")
If you want the Data inside this Array you can Access them as you already did
By reading a JSON file from a local folder, Im trying to generate drawer menu having child items. readJsonDataFromFile(); returns the JSON string. Im using the following code to generate menu.
lstChild = new TreeMap<>();
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String catName = menuItemObject.getString("cname");
JSONArray scatJsonArray = new JSONArray(menuItemObject.getString("csubcat"));
for (int j = 0; j < scatJsonArray.length(); ++j) {
JSONObject scatItemObject = scatJsonArray.getJSONObject(j);
//********GENERATING CHILD ITEMS HERE***********
}
lstChild.put(catName,childItem);
}
} catch (IOException | JSONException exception) {
Log.e(HomeActivity.class.getName(), "Unable to parse JSON file.",exception);
}
lstTitle = new ArrayList<>(lstChild.keySet());
I want to generate child items (childItem) and expected record set is like
List<String> childItem = Arrays.asList("Beginner","Intermediate","Advanced","Professional");
JSON string
[
{
"cid": "1",
"cname": "WATCHES",
"cimg": "074321.png",
"csubcat": [
{
"sid": "1",
"sname": "FASTTRACK"
},
{
"sid": "2",
"sname": "TIMEX"
},
{
"sid": "3",
"sname": "ROADSTER"
},
{
"sid": "4",
"sname": "TITAN"
}
]
}
]
Im beginner to Android/Java. Thanks in advance
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String catName = menuItemObject.getString("cname");
JSONArray scatJsonArray = new JSONArray(menuItemObject.getString("csubcat"));
List<String> childItem = new ArrayList<>();
for (int j = 0; j < scatJsonArray.length(); ++j) {
JSONObject scatItemObject = scatJsonArray.getJSONObject(j);
childItem.add(scatItemObject. getString("sname"));
}
lstChild.put(catName,childItem);
}
} catch (IOException | JSONException exception) {
Log.e(HomeActivity.class.getName(), "Unable to parse JSON file.",exception);
}
I have a json file in the below format:
{
"IsLastPage": false,
"EnrichedData": {
"Base": [
{
"Number": "001107635",
"Type": "EEG_PR"
},
{
"Number": "00110754",
"Type": "ABC_PR"
}
]
}
}
To parse it in java I am using the following piece of code:
JSONObject jsonObject = new JSONObject(new FileReader("src\\enriched.json"));
JSONArray EnrichedData = jsonObject.getJSONArray("EnrichedData");
System.out.println(EnrichedData);
for(int i=0; i < EnrichedData.length(); i++) {
JSONObject row = EnrichedData.getJSONObject(i);
JSONArray elements = row.getJSONArray("Base");
for(int j=0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject Number = element.getJSONObject("Number");
JSONObject Type = element.getJSONObject("Type");
System.out.println("Number: " + Number.getString("Number"));
System.out.println("Type: " + Type.getString("Type"));
}
}
But on executing this it throws exception that
org.json.JSONException: JSONObject["Base"] not found.
What wrong am I doing here?
Note that this is wrong:
JSONArray EnrichedData = jsonObject.getJSONArray("EnrichedData");
EnrichedData is not an array but a JSONObject.
Within this Json response, how do I get access to "smallImageUrls" and get the image url using Java?
Seems like "smallImageUrls" is an array within the "matches" jsonarray. Someone please correct me if I am wrong on that.
{
"attribution":{
"html":"Recipe search powered by <a href='http://www.yummly.com/recipes'><img alt='Yummly' src='http://static.yummly.com/api-logo.png'/></a>",
"url":"http://www.yummly.com/recipes/",
"text":"Recipe search powered by Yummly",
"logo":"http://static.yummly.com/api-logo.png"
},
"totalMatchCount":17663,
"facetCounts":{
},
"matches":[
{
"imageUrlsBySize":{
"90":"http://lh3.ggpht.com/bTkxROvVTjHChEsGLRnkuwPoi-eNrHmESYP3xDHMsIisN-U06z-OfwErSjT5AHvMG0Ccgw8cN4mVqNyjWzbz=s90-c"
},
"sourceDisplayName":"Serious Eats",
"ingredients":[
"mayonnaise",
"crema mexican",
"feta",
"ancho powder",
"garlic",
"coriander leaf",
"shuck corn",
"lime"
],
"id":"Mexican-street-corn-_elotes_-370469",
"smallImageUrls":[
"http://lh5.ggpht.com/itong2VhnBU2mvPtzNimL58MnkC4l113RgNyrEWq8Jf76AsOGOlBoVQyCF-jYDPtzTB-7SoViNzyV5-Xe0NS=s90"
],
"recipeName":"Mexican Street Corn (Elotes)",
"totalTimeInSeconds":2400,
"attributes":{
"cuisine":[
"Mexican"
]
},
"flavors":{
"sweet":0.5,
"sour":0.6666666666666666,
"salty":0.6666666666666666,
"piquant":0.3333333333333333,
"meaty":0.3333333333333333,
"bitter":0.6666666666666666
},
"rating":5
}
],
"criteria":{
"excludedIngredients":null,
"allowedIngredients":null,
"terms":null
}
}
this is the code that I currently have. I can access all the other strings, just not the image urls .
JSONObject resObj = new JSONObject(result);
JSONArray foundrecipes = resObj.getJSONArray("matches");
for(int i = 0;i<foundrecipes.length(); i++){
JSONObject recipe = foundrecipes.getJSONObject(i);
String recipeName = recipe.getString("recipeName");
String rating = recipe.getString("rating");
String id = recipe.getString("id");
String imageurl = recipe.getString("smallImageUrls");
data.add(new Recipes(recipeName, rating, id, imageurl));
}
smallImageUrls, is inside matches that is inside the root, so you have to retrieve matches and, through it, smallImageUrls
JSONObject obj = new JSONObject(...);
JSONArray matches = obj.optJSONArray("matches");
if (matches != null) {
for (int i = 0; i < matchesLenght; i++) {
JSONObject objAtIndex = matches.optJSONObject(i);
if (objAtIndex != null) {
JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls");
for (int j = 0; j < smallImageUrlsSize; j++) {
String urlAtIndex = smallImageUrls.optString(j);
}
}
}
}
i am getting this error using php-mysql and json, seriously i have spent 2 days, so here is my codes
require "includes/connexion.php";
$requete="SELECT * FROM contacts;";
$rep=$pdo->query($requete);
while($data=$rep->fetch(PDO::FETCH_ASSOC)){
$sortie[]=$data;
}
print(json_encode($sortie));
$rep->closeCursor();
here is a part of the java code and the jsonArray in the results parameter contains that value(from the console):
[{"id":"1","nom":"Fedson Dorvilme","email":"fedsondorvilme#gmail.com","phone":"34978238","img":"ic_launcher"},{"id":"2","nom":"Darlene Aurelien","email":"darleneaurelien#yahoo.fr","phone":"34171191","img":"ic_launcher"}]
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);
Log.i("MyLogFlag", "Nom Contact: " + json_data.getString("nom"));
returnString = "\n\t" + array.getJSONArray(i);
System.out.println(" ********** RS [ "+returnString+" ]****************");
}
} catch (Exception e) {
Log.e("log_Exception_tag", "Error parsing data " + e.toString());
}
thanks in advance for your help
This is your json structure:
[
{
"id": "1",
"nom": "Fedson Dorvilme",
"email": "fedsondorvilme#gmail.com",
"phone": "34978238",
"img": "ic_launcher"
},
{
"id": "2",
"nom": "Darlene Aurelien",
"email": "darleneaurelien#yahoo.fr",
"phone": "34171191",
"img": "ic_launcher"
}
]
From your Java code:
JSONArray array = new JSONArray(result); // OK
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i); // OK
returnString = "\n\t" + array.getJSONArray(i); // ??? wrong!!
}
You try to get Array from array but its JSONObject.
Proper way:
JSONArray gb = new JSONArray(str);
for (int j = 0; j < gb.length(); j++) {
JSONObject element = gb.getJSONObject(j);
int id = element.getInt("id");
int phone = element.getInt("phone");
String nom = element.getString("nom");
String email = element.getString("email");
String img = element.getString("img");
}