how to parse json array without "id" - android

Below is my code which parse JSON if I fetch "id". If I don't give id then the JSON array will not show. How do i show JSON without id?
How do I parse JSONArray without "id" if I don't give id in JSON file then array will not show it is necessary to give "id" in JSON file???
this json array not show
{
"status": 1,
"data": [
{
"title": "Elementary"
},
{
"title": "Middle"
},
{
"title": "High"
},
{
"title": "Atypical"
}
]
}
this json array will show
{
"status": 1,
"data": [
{
"id": "1",
"title": "Elementary"
},
{
"id": "2",
"title": "Middle"
},
{
"id": "3",
"title": "High"
},
{
"id": "4",
"title": "Atypical"
}
]
}
Code:
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
// Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("title"));
}

You are accessing the id property here:
Category_ID.add(Long.parseLong(object.getString("id")));
When it is not there this will throw an exception.

Try This Code while parsing your json:
if(object.has("id"))
{
Category_ID.add(Long.parseLong(object.getString("id")));
}
else
{
// add default id
}
hope this will work for you.

I suppose you want your code to work for both JSON samples.
You can perform a check if "id" exists or not and then parse accordingly.
You can perform this check using the below code.
String id = object.optString("id");
//JSONObject.optString("id") will return id's value if it exists or else will return empty string.
if(!"".equals(id)){
Category_ID.add(Long.parseLong(id));
//this code will run only when your JSON contains id
}
else
{
//this code will run when your JSON doesn't have id field.
Category_ID.add();
}

Related

How to get specific data from API request without creating data classes including other data classes?

for example:
{
"error": false,
"message": "",
"code": "",
"ver": "v1.0.0",
"base": "https://,,,,,,,,,.com/",
"count": 1,
"updated": "2020-10-28T19:40:51+03:00",
"data": [
{
"id": "44",
"slug": "human-resources",
"name": "Human resources",
"img1": null,
"img2": "page_44/1560347480_2.jpg",
"date": "2019-05-31",
"des": "'vvvvvv.v",
"sendMail": "info#....",
"iframe_url": "ff/ff"
}
]
}
this is api json response.
I want only "data": [] value, not the rest.
Is there a way I can avoid creating data class for whole api response instead just request "data": [..] value?
I am using Android Studio Kotlin Retrofit Moshi
If I understand your question correctly, you just want to extract data from that JSON string. You can do that with:
JSONArray dataArray;
try {
dataArray = new JSONObject(yourString).optJSONArray("data");
} catch (JSONException e) {
// whatever
}
for (int i = 0; i < dataArray.length(); ++i) {
// do whatever you want with each object:
String name = dataArray.optJSONObject(i).optString("name");
}

Android - Parse a Nested JSON array with Volley

I am really new to JSON Parsing and learning everyday.
I have a specific JSON response I have to parse but I am finding no luck doing it.
I am using Volley for Parsing Request.
Here is my response:
{
"error": false,
"message": "Favourties fetched successfully",
"code": 200,
"data": [
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
},
{
"id": "5f198084c42e1f60854c57e2",
"type": 3,
"status": 1,
"favourite": {
"images": [],
"_id": "5f12d5345478a53584eca98b",
"name": "Water Paint7"
},
"createdAt": "2020-07-23T12:20:20.680Z",
"updatedAt": "2020-07-23T12:20:20.680Z"
}
]
}
I am able to get the Array which contains 2 object, but I am unable to get the data inside the nested favorites.
try {
Log.d("Onresponse", response);
//converting the string to json array object
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject favorites = array.getJSONObject(i);
Log.d("lenght", favorites.getString("status"));
//adding the product to product list
favoriteList.add(new FavoriteVendorsModel(
favorites.getString("firstName"),
favorites.getString("lastName"),
favorites.getString("businessName"),
favorites.getString("image")
));
}
Here is my method.
You have skipped one level of nesting. By calling array.getJSONObject(i) you get:
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
}
And you are trying to call directly on that object next getString methods:
favorites.getString("firstName");
favorites.getString("lastName");
favorites.getString("businessName");
favorites.getString("image");
When actually you must first get JSONObject named favourite and then call these getString method on it:
JSONObject favorite = favorites.getJSONObject("favourite");
favorite.getString("firstName");
favorite.getString("lastName");
favorite.getString("businessName");
favorite.getString("image");

how to parse dynamic size json array using json2pojo plugin

I'm working on an android project where I have to show some items in response of a request I'll send to server using provided API.
I'll get an JSON object in response which contains a JSON array as one of the elements inside of it.
My problem is the JSON array may have several JSON objects inside of it and how to handle this situation is beyond my knowledge.
"Details": [
{
"OrderId": 7615,
"ProductId": 1292406,
"ProductImageFormat": "jpg",
"ProductImageId": 1752,
"ProductImageUrl": "",
"ProductOrgImageUrl": "",
"ProductLargeImageUrl": "",
"ProductName":""
"ProductSlug": ""
"ProductSubTitle": ""
"Quantity": 1,
"UnitPrice": 8300
},
{
"OrderId": 7615,
"ProductId": 23568452,
"ProductImageFormat": "jpg",
"ProductImageId": 1895,
"ProductImageUrl": "",
"ProductOrgImageUrl": "",
"ProductLargeImageUrl": "",
"ProductName":""
"ProductSlug": ""
"ProductSubTitle": ""
"Quantity": 1,
"UnitPrice": 3500
}
]
I may get several of this single object with different values in one Array as you can see above.
Is there anything I can do about this?
EDIT: what I mean is that the array size is dynamic and I don't know how to handle dynamic sized JSON array
first of all, the JSON you provided is invalid. So I'm going to correct it and assume the following (the "Details" array is wrapped in a JSONObject)
{
"Details": [
{
"OrderId": 7615,
"ProductId": 1292406,
"ProductImageFormat": "jpg",
"ProductImageId": 1752,
"ProductImageUrl": "",
"ProductOrgImageUrl": "",
"ProductLargeImageUrl": "",
"ProductName":"",
"ProductSlug": "",
"ProductSubTitle": "",
"Quantity": 1,
"UnitPrice": 8300
},
{
"OrderId": 7615,
"ProductId": 23568452,
"ProductImageFormat": "jpg",
"ProductImageId": 1895,
"ProductImageUrl": "",
"ProductOrgImageUrl": "",
"ProductLargeImageUrl": "",
"ProductName":"",
"ProductSlug": "",
"ProductSubTitle": "",
"Quantity": 1,
"UnitPrice": 3500
}
]
}
Get the array and iterate it (assuming the outer object is called jo):
try {
JSONArray ja = jo.getJSONArray("Details");
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
Log.i("JSON", jsonObject.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
This way you can handle JSON arrays of arbitrary length.

How to parse this JSON file to some ArrayList<String>?

in the past i have already parsed a json file from url to local sqlite database and the json source was like the following one:
[
{
"origin": "accommodation",
"parent": "",
"en": "Accommodation"
},
{
"origine": "book",
"parent": "shopping",
"en": "Book"
},
{
"origin": "university",
"parent": "education",
"en": "University"
}
]
But now it seems to be different. I validate the following json file so i'm sure it is a valid json, but it is formatted in a different way, so i do not know how to parse it in the right way. In addition this time i would put the content in an ArrayList. Here is the json file:
{
"city1": {
"item1": {
"score": 6196.58,
"step": 0.00423,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 106.86,
"step": 2.5822,
"name": "User 2",
"form": "yellow"
},
"item3": {
"score": 671.48,
"step": 0.387,
"name": "User 3",
"form": "yellow"
},
},
"misc": {
"online_users": {
"kind1": 18,
"kind2": 3
},
"ops": [
""
]
},
"city2": {
"item1": {
"score": 6196.58,
"step": 0.00405,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 179563.93,
"step": 0.000138,
"name": "User 2",
"form": "yellow"
},
"min_size": {
"line": 10
},
"out_of_sync": [
"0e888069530497506433b5f0cacb",
"b428fa3a9b9e13cf8b26196bfcc7",
"f42442a2e46523f059809f83f1a9"
],
},
}
Can you tell me how to handle these values and how to put in some arraylist?
There are several ways to do this, but I'll post the way I feel like makes the most sense. If you don't mind putting this in separate arrays you can do this:
String stringOfJSONCode = <read in the JSON here>;
JSONObject json = new JSONObject(stringOfJSONCode);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (Exception e) {
}
}
You need to use an iterator to loop through a JSONObject. You could use any other loop to loop through JSONArrays. This will iterate through the outer objects, like city1, misc, city2. The key will be either city1, misc, or city2.
If you want to get those, just add this within the 'try'
JSONObject object = json.getJSONObject(key);
or
JSONArray array = json.getJSONArray(key);
depending on what you're trying to get. Once you have these, you can do the following:
JSONObject city1 = object.getJSONObject("item1");
List<String> jsonList = new ArrayList<String>();
jsonList.add(object.getDouble("score"));
jsonList.add(object.getDouble("step"));
jsonList.add(object.getString("name"));
jsonList.add(object.getString("form"));
If you are not sure if it will be item1 or whatever, you can iterate through it again using the iterator and add each item in dynamically. Also you can make another try-catch, try to get a JSONArray, if it is not an array it will go in the catch, and then iterate through the object.
You could also make a hashmap or 2D array to add everything in the same array.
Hope this helps
Why don't you let jackson mapper do it's magic?
The only thing you'll need then would be appropriate DTO classes.

How to parse this JSON data using GSON? and put it into an ArrayList

I am trying to parse data from a MongoDB cloud server. My JSON data returned from the server is as follows:
[
{
"_id": {
"$oid": "4e78eb48737d445c00c8826b"
},
"message": "cmon",
"type": 1,
"loc": {
"longitude": -75.65530921666667,
"latitude": 41.407904566666666
},
"title": "test"
},
{
"_id": {
"$oid": "4e7923cb737d445c00c88289"
},
"message": "yo",
"type": 4,
"loc": {
"longitude": -75.65541383333333,
"latitude": 41.407908883333334
},
"title": "wtf"
},
{
"_id": {
"$oid": "4e79474f737d445c00c882b2"
},
"message": "hxnxjx",
"type": 4,
"loc": {
"longitude": -75.65555572509766,
"latitude": 41.41263961791992
},
"title": "test cell"
}
]
The problem I am having is the data structure returned does not include a name of the array of JSON objects. Each object returned is a "post". But how do I parse it using GSON if the there is no name for the array of JSON objects. I would like to put these "posts" into an ArrayList of type Post.
Piece of code you are looking for:
String jsonResponse = "bla bla bla";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType);
Use the contructor for JSONArray to parse the string:
//optionally use the com.google.gson.Gson package
Gson gson = new Gson();
ArrayList<Post> yourList = new ArrayList<Post>();
String jsonString = "your string";
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++){
Post post = new Post();
//manually parse for all 5 fields, here's an example for message
post.setMessage(jsonArray.get(i).getString("message"));
//OR using gson...something like this should work
//post = gson.fromJson(jsonArray.get(i),Post.class);
yourList.Add(post);
}
Considering there are only 5 fields, using Gson might be more overhead than you need.

Categories

Resources