json parsing and storing in an arraylist in Phonegap - android

in my app when the user clicks a button, it hits an url and i use to get a return data in json format as follows
{
"Status":
{
"image":
[
{
"Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316145577.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316145577.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316146270.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316146270.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316146473.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316146473.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316147003.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316147003.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316581422.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316581422.jpg"
},
{ "Large" : "http://XXXXXXXXXXXXXXXXXX.com/images/original/1316694587.jpg",
"Small" : "http://XXXXXXXXXXXXXXXXXX.com/images/thumb70/1316694587.jpg"
}
]
}
}
i want to do json parsing and store the URLs named under Large to be stored in an Array and URLs named under Small to be stored in another array. I want this to be done using javascript.
For example in my app in another url my json data is to be as follows
{"Status":[{ "Id": "46", "Username": "guru" }]}
For this i use to get the data as
var data = JSON.parse(my_JSON_object);
var id = data.Status[0].Id;
var name = data.Status[0].Username;
But how to parse for the json array mentioned first.
How to do this, pls help me friends

i got the answer by this way
var data = JSON.parse(my_JSON_object);
var image = [];
for(var i=0; i< image.length(); i++)
{
image[i] = data.Status.image[0].Large;
alert(image);
}
alert(image);

Related

Need help parsing this type of json in Android using retrofit for API response handling

Please show me a way to make a proper model for this JSON so that I get "Indian Premier League" as the key and the array next to it as value. We can have multiple leagues as well in the json.
{
"keySeriesNews": {
"Indian Premier League": [
{
"id": 203,
"slug": "tata-ipl-2022-why-delhi-capitals-bought-shardul-thakur-for-inr-1075-crore",
"competition_id": 3269,
"image_id": 1203,
"image_caption": "Shardul Thakur in action",
"start_date": "2022-03-05 17:25:38",
"created_at": "2022-03-05 12:08:19",
"updated_at": "2022-04-15 06:50:30",
"headline": "TATA IPL 2022: Why Delhi Capitals bought Shardul Thakur for INR 10.75 crore",
"sport_id": 15,
"image": {
"id": 1203,
"file_name": "shardulthakur_new.webp",
"created_at": "2022-04-15 06:47:41",
"image_path": "https://stagingkisma.6lgx.com/storage/images/shardulthakur_new_320x320.webp"
},
"competition": {
"id": 3269,
"slug": "indian-premier-league-2",
"competition_name": "Indian Premier League"
}
}
]
}
}
I have used this model to parse in retrofit but it is not fetching any data from the API. It is completely blank. No data in it.
data class HomeNewsParentModel(
#SerializedName("keySeriesNews" ) var keySeriesNews: JSONObject? = JSONObject()
)
However, when I use this model, it fetches data and I can access it. But problem is that it is hardcoded. I mean, these models will not capture data if the league name changes in any case. Here are the models which captured data.
data class HomeNewsParentModel(
#SerializedName("keySeriesNews" ) var keySeriesNews: KeySeriesNews? = KeySeriesNews()
)
data class KeySeriesNews (
#SerializedName("Indian Premier League" ) var league : ArrayList<League> = arrayListOf()
)
data class League (
#SerializedName("id" ) var id : Int? = null,
#SerializedName("slug" ) var slug : String? = null,
#SerializedName("competition_id" ) var competitionId : Int? = null,
#SerializedName("image_id" ) var imageId : Int? = null,
#SerializedName("image_caption" ) var imageCaption : String? = null,
#SerializedName("start_date" ) var startDate : String? = null,
#SerializedName("created_at" ) var createdAt : String? = null,
#SerializedName("updated_at" ) var updatedAt : String? = null,
#SerializedName("headline" ) var headline : String? = null,
#SerializedName("sport_id" ) var sportId : Int? = null,
#SerializedName("image" ) var image : Image? = Image(),
#SerializedName("competition" ) var competition : Competition? = Competition()
)
I have coded for a parser on the generic side to handle key-value type JSON like this but the JSON object was empty when I used the first approach of the data model. I need to make a generic parser to fetch league names as well as their data in key-value format since there can be multiple leagues that can come in this response as well.
PS: This is my parser which is getting empty JSON Object
private fun parseJSONData(data: JSONObject){
try {
val jsonObject = JSONObject(data)
for (key in jsonObject.keys()) {
Toast.makeText(
this#SeriesFragment.requireContext(),
"Key : " + key + " Value: " + jsonObject.optString(key),
Toast.LENGTH_SHORT
).show()
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
Your help is much appreciated. Thanks.
Just a tip - if you already have the JSON available, you can use this plugin to easily generate a first draft of your model and adapt it if needed.
Some questions:
If you can have multiple leagues in your response, shouldn't keySeriesNews also be a list and not just a JSON object? For example like this:
{
"keySeriesNews": [
{
"id": 203,
"title": "Indian Premier League",
"slug": "tata-ipl-2022-why-delhi-capitals-bought-shardul-thakur-for-inr-1075-crore",
"competition_id": 3269,
"image_id": 1203,
...
}
]
}
What's your reasoning for handling JSON manually instead of using a ConverterFactory?
Where and how are you calling parseJsonData?
Well, I am not sure about this is correct or not. If anyone has a standard way of doing it, it is much appreciated. However, I have used the JSONElement instead of JSONObject or JSONArray and have used Map to handle key-value type data in my model, and GSONConvertorFactory has got this one right and fetched data correctly. This is the model I used:
data class HomeNewsParentModel(
#SerializedName("keySeriesNews" ) var keySeriesNews: HashMap<String, JsonElement>? = HashMap()
)
And I will parse JSONElement in my parseJsonData function to handle the key-value of this nonstandard JSON coming from API.
Hope this helped you in some way.

Json formation Getting corrupted

I am using JSONObject to create a new json in my Android Application.
But I am experiencing a strange issue where I am observing that my json field names are getting replaced by letters like "a" : "value " , "b " : "value_1" , "c" : value2 "
This works fine for smaller number of childs but as the number grows it distorts the json :
example json :
{
"Employees" : [
{
"userId":"rirani",
"jobTitleName":"Developer",
"firstName":"Romin",
"lastName":"Irani",
"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani#gmail.com"
},
{
"userId":"nirani",
"jobTitleName":"Developer",
"firstName":"Neil",
"lastName":"Irani",
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"neilrirani#gmail.com"
},
{
"userId":"thanks",
"jobTitleName":"Program Directory",
"firstName":"Tom",
"lastName":"Hanks",
"preferredFullName":"Tom Hanks",
"employeeCode":"E3",
"region":"CA",
"phoneNumber":"408-2222222",
"emailAddress":"tomhanks#gmail.com"
}
]
}
Corrupted output :
{
"Employees" : [
{
"a":"rirani",
"b":"Developer",
"c":"Romin",
"d":"Irani",
"e":"Romin Irani",
"f":"E1",
"g":"CA",
"h":"408-1234567",
"i":"romin.k.irani#gmail.com"
},
{
"a":"nirani",
"b":"Developer",
"c":"Neil",
"d":"Irani",
"e":"Neil Irani",
"f":"E2",
"g":"CA",
"h":"408-1111111",
"i":"neilrirani#gmail.com"
},
{
"a":"thanks",
"b":"Program Directory",
"c":"Tom",
"d":"Hanks",
"e":"Tom Hanks",
"f":"E3",
"g":"CA",
"h":"408-2222222",
"i":"tomhanks#gmail.com"
}
]
}
Is this a bug in the Android JSON object ? Any hints?
this issue based on proguard rules in app level gradle file to that value make false like below ..
minifyEnabled false
other wise you can add key in your pojo class like
#SerializedName("userId") // pass your json key
private String userId;

Unable parse the json data in android even by following the actual procedure

iam trying to parse the json data which is shown below.i got output for other Json response by following this procedure but for this i cant get data.
{
"totalResults": 7,
"startIndex": 1,
"hasMoreResults": false,
"itemsPerPage": 10,
"results": [
{
"offering_temp_id": {
"displayName": "Cool Course",
"id": "cours000000000004841",
"course_no": "00006081",
"version": null
},
"delivery_id": {
"displayName": "Instructor-Led",
"id": "eqcat000000000000004"
},
"student_id": {
"id": "emplo000000006156648",
"displayName": "Venkat Rao",
"person_no": "VRAO"
},
"reg_no": "00008341",
"wlist_on": "2017-08-17T08:59:39.843-0400",
"wlist_priority": 5,
"Max_Count": null,
"Current_Count": null,
"is_no_show": false,
"is_walk_in": false,
"offering_action_id": {
"id": "ofapr000000000013441",
"displayName": "00009081"
},
"class_id": {
"id": "class000000000006981",
"displayName": "Cool Course"
},
"elements_to_complete": 0,
"status": "100",
"id": "regdw000000000012581"
},
// total 7 fields
],
"facets": []
}
And iam using the parser procedure as follows
public class EnrollmentParser {
public ArrayList<EnrollmentData> getData(String respnose)//EnrollmentData is my pojo class contains 4 strings and its getters and setters
{
ArrayList<EnrollmentData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(respnose);
JSONArray array = mainObj.getJSONArray("results");
for(int i = 0;i<array.length();i++)
{
EnrollmentData data = new EnrollmentData();
JSONObject resObj = array.getJSONObject(i);
data.setReg_num(resObj.getString("reg_no"));
data.setElements_to_complete(resObj.getString("elements_to_complete"));
data.setW_list_on(resObj.getString("wlist_on"));
data.setW_list_priority(resObj.getString("wlist_priority"));
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
}
when iam trying to display the dataList returned from above method i didnt get any data i got response like
Suggest me any changes that are required to get the response
There is no faulty parsing code, everything is fine (although better use optString).
By default , the toString function will return the type '#' reference value so
You need to override toString in EnrollmentData class to see the actual content inside EnrollmentData object
You can also collect your list objects as single string using
String str = Arrays.toString(yourList.toArray());
How to print out all the elements of a List in Java?
Why don't you use Gson to convert json into object easily instead of getting the field and set them one by one?
You may check out
https://github.com/google/gson

Laravel display results of an array as single json object

Is there a way I can get my response to be a single object with an array of users using Eloquent?
For instance:
{
"results" : [
{ "email" : "test1#test.ca" },
{ "email" : "test2#test.ca" }
]
}
Current it outputs like this:
[
{
"email": "test1#test.ca",
},
{
"email": "test2#test.ca",
}
]
This is how I'm displaying users from my code:
$users = User::whereIn('number', $numbers)->select('email')->get();
return $users;
Which would be fine but I'm using Volley for Android using JSONObjectRequest but its failing when it tries to parse the JSON because it can't parse the array.
You can try it like this:
$users = User::whereIn('number', $numbers)->select('email')->get();
return Response::json(array('results' => $users));

Parsing JSON, array within an array (Android)

I'm trying to parse weather information from a http://www.worldweatheronline.com JSON feed. This is the format that it comes in:
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "100",
"observation_time" : "10:01 PM",
"precipMM" : "0.0",
"pressure" : "1015",
"temp_C" : "3",
"temp_F" : "37",
"visibility" : "4",
"weatherCode" : "143",
"weatherDesc" : [ { "value" : "Mist" } ],
"weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png" } ],
"winddir16Point" : "N",
"winddirDegree" : "360",
"windspeedKmph" : "11",
"windspeedMiles" : "7"
} ],
So there is the current_condition JSONArray, which I have managed to obtain values from. But then how do I read the values from the inner arrays weatherDesc or weatherIconUrl?
Here is my code for reading precipMM, pressure, temp_C, etc:
String precipMM = null;
try {
JSONObject data = json.getJSONObject("data");
JSONArray current_condition = data.getJSONArray("current_condition");
for(int i = 0; i < current_condition.length(); i++) {
precipMM = current_condition.getJSONObject(i).getString("precipMM");
}
} catch (JSONException e) {
e.printStackTrace();
}
It's as simple as
current_condition.getJSONArray()
As also with json parsing I would suggest looking at this library
http://jackson.codehaus.org/
EDIT After you comment
The code you posted could be improved a lot. You are iterating through the array for each value. You can do the same thing with the array. Just call .getJsonArray(), instead of .getJsonObject(). However this means your code is throwing an error for each of the other values. I would again recommend the Jackson library
weatherDesc and weatherIconUrl are provided as array, so you can access by item i.e. inside a for loop.
Just use same command as you do it for current_condition

Categories

Resources