How to fetch data from json API with three level - android

I am stuck in fetching data from json api. many times try but result is unsuccessful. Here is json pattern:
{
"All": [{
"MainCategory": {
"AllData": [{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_CHO1.jpg",
"MainImage": "rsz_0_400_CHO1.jpg",
"MainSmallImages": "rsz_0_100_CHO1.jpg"
}, {
"MainBigThumb": "rsz_0_800_CHO100.jpg",
"MainImage": "rsz_0_400_CHO100.jpg",
"MainSmallImages": "rsz_0_100_CHO100.jpg"
},
{
"MainBigThumb": "rsz_0_800_CHO101.jpg",
"MainImage": "rsz_0_400_CHO101.jpg",
"MainSmallImages": "rsz_0_100_CHO101.jpg"
}
],
"Attribute_Name": "Chocolate",
"Attribute_Value": "123",
"StockKeepingunit": null
}
},
{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_CRI100.jpg",
"MainImage": "rsz_0_400_CRI100.jpg",
"MainSmallImages": "rsz_0_100_CRI100.jpg"
},
{
"MainBigThumb": "rsz_0_800_CRI101.jpg",
"MainImage": "rsz_0_400_CRI101.jpg",
"MainSmallImages": "rsz_0_100_CRI101.jpg"
}
],
"Attribute_Name": "Crisps",
"Attribute_Value": "124",
"StockKeepingunit": null
}
}
],
"Attribute_Name": "Confectionery",
"Attribute_Value": "122",
"StockKeepingunit": null
}
},
{
"MainCategory": {
"AllData": [{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_YP100.jpg",
"MainImage": "rsz_0_400_YP100.jpg",
"MainSmallImages": "rsz_0_100_YP100.jpg"
}],
"Attribute_Name": "Sub-Category",
"Attribute_Value": "163",
"StockKeepingunit": null
}
}],
"Attribute_Name": "Your Category",
"Attribute_Value": "162",
"StockKeepingunit": null
}
}
],
"status": {
"message": "success",
"result": 1
}}
the data format is like
1. MainCategory1
1.1 Subcategory1
1.1.1 Product1
1.1.2 Product2
1.2 Subcategory2
1.2.1 Product1
1.2.2 Product2
2. MainCategory2
2.1 Subcategory1
2.1.1 Product1
2.1.2 Product2

You can use retrofit for it and convert your whole json data into Gson, which will make it a lot more easier.
first of all copy the response of your API and create your bean classes through
this site * By clicking source type to JSON * Annotation Style to GSON * Unticking useDoubleNumbers * Unticking AllowAdition Property
then copy those files to your project
then in your activity
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIServiceInterface apiController = retrofit.create(APIServiceInterface.class);
Call<Bean> result = apiController.studentLogin(username,password);
result.enqueue(new Callback<Bean>() {
#Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
// you will get the reponse in the response parameter
}
#Override
public void onFailure(Call<Bean> call, Throwable t) {
}
});
Where APIServiceInterface is the interface file.

It's simple, but you have to be cautious about the {}, [] and , while parsing Json. I will not write parsing code for you, instead just give an idea.
Intitial Json Response Object
Exract JsonArray named as "All" from above object
Get first Position Of above array, you will get an JsonObject
Extract a JsonObject from above object with name "MainCategory"
Exract JsonArray named as "AllData" from above object
Get first Position Of above array, you will get an JsonObject
Extract a JsonObject from above object with name "SubCategory"
Exract JsonArray named as "AllData" from above object
Get first Position Of above array, you will get an JsonObject
Containing following data,
"MainBigThumb": "rsz_0_800_CHO1.jpg",
"MainImage": "rsz_0_400_CHO1.jpg",
"MainSmallImages": "rsz_0_100_CHO1.jpg"

i solved my problem here are json parsing as per below.
JSONObject jsonObj = new JSONObject(json);
JSONArray AllJsonArray = jsonObj.getJSONArray("All");
for (int i = 0; i < AllJsonArray.length(); i++) {
JSONObject AllJsonObject = AllJsonArray.getJSONObject(i);
JSONObject mainCategoryJsonObject = AllJsonObject.getJSONObject("MainCategory");
String mainCategoryName = mainCategoryJsonObject.getString("Attribute_Name");
String mainCategoryValue= mainCategoryJsonObject.getString("Attribute_Value");
JSONArray AllData1JsonArray = mainCategoryJsonObject.getJSONArray("AllData");
for (int j = 0; j < AllData1JsonArray.length(); j++) {
JSONObject AllData1JsonObject = AllData1JsonArray.getJSONObject(j);
JSONObject subCategoryJsonObject = AllData1JsonObject.getJSONObject("SubCategory");
String subCategoryName = subCategoryJsonObject.getString("Attribute_Name");
String subCategoryValue = subCategoryJsonObject.getString("Attribute_Value");
JSONArray AllData2JsonArray = subCategoryJsonObject.getJSONArray("AllData");
for (int k = 0; k < AllData2JsonArray.length(); k++) {
JSONObject AllData2JsonObject = AllData2JsonArray.getJSONObject(k);
String MainBigThumb = AllData2JsonObject.getString("MainBigThumb");
String MainImage = AllData2JsonObject.getString("MainImage");
String MainSmallImages = AllData2JsonObject.getString("MainSmallImages");
}
}
}

Related

Using Kotlin to parse nested json array/object

I've read a few posts on here saying to use gson or something else.
Android Kotlin parsing nested JSON
I am planning on switching to gson later but wondering how to parse with kotlin.
JSON object:
{
"childScoresList": [
{
"child_id": "1",
"score_date": "2022-03-27",
"category_id": "1",
"category_name": "Preschool Math",
"classes": [
{
"category_name": "Preschool Math",
"class_name": "Number Blocks",
"class_id": "1",
"class_description": "Ones, Tens, Hundreds Blocks used to create given numbers.",
"skills": [
{
"skill_id": "1",
"skill_name": "Place Value",
"skill_description": "Knowing the place value of specific elements.",
"skill_score": "50"
}
]
}
]
}
]
}
Kotlin code:
val obj = JSONObject(response.toString())
val jsonArray = obj.getJSONArray("childScoresList")
for (i in 0 until jsonArray.length()) {
val categoryName = jsonArray.getJSONObject(i).getString("category_name")
}
How do I get data in class_name?
I tried various things but could not get it to work.
You must first get JSONArray from the object according to the following code and then access the class_name variable
val obj = JSONObject(js)
val jsonArray = obj.getJSONArray("childScoresList")
for (i in 0 until jsonArray.length()) {
val classes = jsonArray.getJSONObject(i).getJSONArray("classes")
for (x in 0 until classes.length()) {
val categoryName = classes.getJSONObject(x).getString("category_name")
val className = classes.getJSONObject(x).getString("class_name")
}
}

object value is showing using JSON parsing for object and string with same name

Hi in the below not going inside of the JSON object block and does not returning anything .in the below response if the value is a JSON object it should return the value .if is not object it should go to else block and returning the string.
can anyone help me to resolve the issue?
response:
{
"name": "account_id",
"value": {
"value": "11x52925",
"label": "VS Hospital"
},
"label": "Account Name",
"uitype": "51",
"type": {
"defaultValue": null
}
},
accounts.java:
if (name.equals("account_id")) {
Object values = synFields1.getValue();
try {
if (values instanceof JSONObject) {
JSONObject jsonObject1 = new
JSONObject(String.valueOf(synFields1.getValue()));
String value = jsonObject1.getString("label");
account_name.add(value);
}
else if (values instanceof String) {
//here, you get a string
//account_name.addAll(value);
String value_names = String.valueOf(synFields1.getValue());
String value_label = String.valueOf(synFields1.getLabel());
// Log.e("account_name",
String.valueOf(account_name.add(value)));
account_name.add(value_label );
//account_name.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Expected output: VS Hospital
Make object using GSON
here is tested code
Gson g = new Gson();
String jsonString = "{\"name\": \"account_id\", \"value\": { \"value\": \"11x52925\", \"label\":\"VSHospital\" },\"label\":\"Account Name\", \"uitype\": \"51\", \"type\": { \"defaultValue\": null }}";
Example p = g.fromJson(jsonString, Example.class);
Log.d("dsds",p.getValue().getLabel() );
Make POJO using http://www.jsonschema2pojo.org/
add GSON in gradle
implementation 'com.google.code.gson:gson:2.8.6'

Parsing Json array inside jsonobject in android

[
{
"subject": "Top exotic beaches in Greece",
"participants": [
"Aristotle", "Socrates"
],
"preview": "Plato,\nThis is what I was talking about for the bachelor party!",
"isRead": false,
"isStarred": true,
"ts": 1471451322,
"id": 5
}
]
How to parse "participants" from this json... thanx in advance
JSONArray jsonArray = new JSONArray(mainJSON.getJSONArray("participants"))
Then you just use your object like this:
jsonArray.getJSONObject(0)
try {
JSONArray participants = jsonObject.getJSONArray("participants")
for (int i = 0; i < participants.length(); i++) {
yourArrayList.add(participants.getString(i))
}
} catch(JSONException e) {
// Handle exception.
}

JSONArray strange behavior for different API Versions

I have a problem with JSONArray. My JSONArray works on API 22 but not on a device with API less than 22.
When I change my compile sdk I get tons of errors.
Is there any solution for this strange behavior. I can't explain it...
This is the JSON:
{"2":"[{\"id\":\"3\",\"value\":\"1.15\",\"name\":\"Knobi\"}, Dressing]","1":"[{\"id\":\"1\",\"value\":\"0.00\",\"name\":\"Scharf\"}, Soße, {\"id\":\"2\",\"value\":\"1.00\",\"name\":\"Tzatziki\"}, Soße]"}
if(addonsJSON != null)
{
Iterator<String> iterator = addonsJSON.keys();
while (iterator.hasNext())
{
String theKey = iterator.next();
System.out.println(addonsJSON.get(theKey));
JSONArray values = addonsJSON.getJSONArray(theKey);
for (int j = 0; j < values.length(); j+=2)
{
JSONObject vals = new JSONObject(values.getString(j));
CartChild cartChild = new CartChild();
cartChild.name = vals.getString("name");
cartChild.price = vals.getString("value");
itemtotal += Float.parseFloat(vals.getString("value"));
childsList.add(cartChild);
}
}
}
your json is not a valid json text. You can't iterate over invalid json
modify it like that
{
"1": [
{
"id": "1",
"value": "0.00",
"name": "Scharf"
},
"Soße",
{
"id": "2",
"value": "1.00",
"name": "Tzatziki"
},
"Soße"
],
"2": [
{
"id": "3",
"value": "1.15",
"name": "Knobi"
},
"Dressing"
]
}
compare your json and mine on http://jsonlint.com/
The problem was that I convert the HashMap to a JSONObject. After that I saved my JSONObject as a String to SugarORM. The convertion was the fault!
So I tried it with GSON. Now it works.
So just use this:
Gson gson = new Gson();
String json = gson.toJson(hashmap);

Count the json objects inside json Array in Android?

I am trying to parse json values into my Android application. Here i am stuck at a place wherein I need to have the objects length inside the json arraylist.
Below is my json:
"events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
Now my question is how do I parse to get the length of the json array like:
2012-11-30 count = 1
2013-08-17 count = 1
2013-09-27 count = 2
How do I loop the json array using the date's as they are json object and find the length of each of the json array dates. I want count of each array individually over here.
Would I need to add a key value kind of pair in the json array "dates" so as I can have a for loop to get the count of the values inside the array?
Thank you in advance
Try Below Code and count objects using length of JsonArray:
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String key = keys.next();
try{
JSONArray array = jObject.getJSONArray(key);
//count objects values using array length.
}
catch(Exception e){
e.printStackTrace()
}
}
String jstr = jso.getString("Events");
JSONObject mdcalkey = new JSONObject(jstr);
Iterator iter = mdcalkey.keys();
ArrayList<String> arr = new ArrayList<String>();
ArrayList<String> arrTimeDate = new ArrayList<String>();
ArrayList<String> arrtype = new ArrayList<String>();
while (iter.hasNext()) {
arr.add((String) iter.next());
}
// ja = mdcalkey.getJSONArray(arr.get(0));
jar = new JSONArray[arr.size()];
This arr array will display all dates array..please check it..if any query then tell me.
You can iterate over the keys in your JSONObject and check if their corresponding values are JSONArrays, then store their lengths in a map:
Iterator iter = yourJSONObject.keys();
while (iter.hasNext())
{
String key = (String) iter.next();
JSONArray array = yourJSONObject.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
String json = "events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
try {
JSONObject obj = new getJSONObject(new JSONObject("{"+"json"+"}").getJSONObject("events").toString());
Iterator iterator = obj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONArray array = obj.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
}
catch (JSONException e)
{
// handle exception here
}

Categories

Resources