Django JsonResponse parsing error in Android - java

This is the JSON response I am getting from the server :
{
"0": {
"pk": 41,
"fields": {
"heading": "Empty Lecture Slot",
"notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00",
"date": "2018-04-25",
"priority": 1,
"has_read": false,
"action": "/dashboard/set_substitute/91959"
},
"model": "Dashboard.specificnotification"
}
}
Here is the Java code used for parsing this JSON object :
JSONObject jsonObject = new JSONObject(response);
This is the error I am getting in the catch block :
org.json.JSONException: No value for {"0": {"pk": 41, "fields": {"heading": "Empty Lecture Slot", "notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00", "date": "2018-04-25", "priority": 1, "has_read": false, "action": "/dashboard/set_substitute/91959"}, "model": "Dashboard.specificnotification"}}
How do I parse this object in Android.

Im not sure, but doesn't JSON arrays start like this?:
[
{
}
]
Also the "0" seems to be not required. It will be automatically ordered
EDIT: you can also check online if your json is valid. Just google Json formatter.

Related

Parsing JSON response when returned as Array

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
This is the error I continue to get while attempting to parse my incoming JSON response data. I'm utilizing the OkHttp library to create and call, and the API I'm getting results from returns everything in an Array as follows:
[
{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
I found a lot of folks recommending Gson to parse it into a custom class, but the following code, in theory, should work and it isn't. The parsing doesn't even begin due to it expecting BEGIN_OBJECT and it being BEGIN_ARRAY:
String jsonData = response.body().string();
Gson gson = new Gson();
EventInfo test = gson.fromJson(jsonData, EventInfo.class);
class EventInfo {
String imageURL;
String name;
JSONArray series;
}
You are trying to parse it into an object. But in your response, you can clearly see that it's a list. The parent POJO should have been a list. And inside that list, you should have created another POJO.
In your response parent is found as array but you need to add first parent as JSON object and child as a array or object.
You need response like this
{
"YourArrayName":[
"YourChildObjName":{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
}
I hope this can help You!
Thank You
So, I figured it out. Originally I was receiving the same error at a later point; namely when it got to the series key value in the first JSONObject. The original error occurred because I was trying to parse series as a JSONArray, rather than a List<JSONObject> The corrections are below:
String jsonData = response.body().string();
Gson gson = new Gson();
Type listType = new TypeToken<List<EventInfo>>() {}.getType();
List<EventInfo> test = gson.fromJson(jsonData, listType);
And the EventInfo class:
class EventInfo {
String imageURL;
String name;
List<JSONObject> series;
}
Thank you for the advice everyone!

How to change the key name in nested json before respone in java

While getting the output from an api response it is showing ArrayList as a key, but I want to customize it according to my preference.
Actual json:
{
"ArrayList": [
{
"id": 507,
"version": 1,
"invoiceNumber": "INV16",
"deleted": false
}
}
I need it like this:
{
"invoice": [
{
"id": 507,
"version": 1,
"invoiceNumber": "INV16",
"deleted": false
}
}
This is not an elegant solution, but a json is just a String, you can replace ArrayList with invoice

Android: org.json.JSON.typeMismatch

I've got a method below, which is parsing JSON. However I've run into an error (which you can see from the title), where it is saying "org.json.JSON.typeMismatch" .
Trying to log the names that are getting output however having no luck. I've little experience with cracking JSON (as you can probably tell from this), so wondering how to go about fixing this issue.
private Boolean parse()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo;
realms.clear();
for (int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name = jo.getString("name");
Log.d("",name);
//realms.add(name);
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
And the JSON I am trying to parse into here is:
{
"realms": [{
"type": "pvp",
"population": "low",
"queue": false,
"status": true,
"name": "Aegwynn",
"slug": "aegwynn",
"battlegroup": "Misery",
"locale": "de_DE",
"timezone": "Europe/Paris",
"connected_realms": ["aegwynn"]
}, {
"type": "pve",
"population": "low",
"queue": false,
"status": true,
"name": "Aerie Peak",
"slug": "aerie-peak",
"battlegroup": "Reckoning / Abrechnung",
"locale": "en_GB",
"timezone": "Europe/Paris",
"connected_realms": ["bronzebeard", "aerie-peak"]
}]
(there is more to this but I'd rather not copy it all)
Not sure if perhaps I'm not addressing the "realms" array? Just would appreciate any help on this! As I can't see quite why I'm getting a mismatch?
Kind Regards
J G
Your JSON string show up here it is a JSONObject not a JSONArray, so that you must init an JSONObject with this string, after that get a JSONArray with name realms from previous JSONObject. Here is an example for your reference

How do I convert a list represented as a string to a list?

I am building an Android application which reads from themoviedb.org.
What I am trying to do is have the user enter a movie title and use that title to find its id.
When I run the query to search for movies, I get a response like:
{
"page": 1,
"results": [
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
}
Using the Maven JSON library, I can fetch the results key as a string using json.get("results").
returning:
[
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
But I want to convert the first of these results to another JSONObject so that I can get the movie's id from the first result.
I'm thinking that the way to do this is to convert the results value to a list of JSONObject and then use the json.get("id") method on the first object in the list. But I do not know how to do this conversion.
Any help would be appreciated.
You can use JSONObject.getJSONArray to get the result directly as a JSON Array:
JSONArray results = json.getJSONArray("results") // Get results as JSON Array
JSONObject first = results.getJSONObject(0) // Get first object as JSON Object
See: JSONObject#getJSONArray(String)

org.json JsonObject.has() returning true for key that doesn't exist

Edit - Resolved:
The issued turned out to be a combination of our logging code and how json.org handles the distinction between Javascript null and Javascript undefined. Our logging code didn't print null values in objects, so although the json object I saw had no "invoice" field, the actual input had a null "invoice" field. JSONObject's .has() method reported that there was an "invoice" field, but when I tried to access it, it's value was null so it wasn't possible to access it. Replacing the .has() check with a .isNull() check (which considers both absent fields and null values) resolved the problem.
In my Google App Engine application, we parse webhook data in the form of json and go down different code paths depending on the presence of a certain key in the json object - if $.data.object.invoice exists we do some work, otherwise we don't. However, when running in production, this detection seems to be broken. I do a simple
jsonObject.getJSONObject("data").getJSONObject("object").has("invoice")
to check for the invoice key and sometimes this returns true even when the invoice key doesn't exist. I came across this error because we do make use of the invoice value when it exists, and I was getting JSONExceptions trying to access it, even though it was protected by a has() check. I added the following logging to ensure that I was doing everything correct:
boolean isAutomaticCharge = jsonObject.getJSONObject("data").getJSONObject("object").has("invoice");
boolean doesGettingStringWork;
try {
jsonObject.getJSONObject("data").getJSONObject("object").getString("invoice");
doesGettingStringWork = true;
}
catch (JSONException e) {
doesGettingStringWork = false;
}
Logger.log("The value of automatic charge is: " + isAutomaticCharge);
Logger.log("Geting the invoice worked? " + doesGettingStringWork);
Logger.log(jsonObject.getJSONObject("data").getJSONObject("object").toString());
if (isAutomaticCharge) {
handleFailedCharge(jsonObject);
}
else {
//Manual Charge
}
And in production the following data resulted in isAutomaticCharge being true and doesGettingStringWork being false:
{
"id": "evt_16vC0s1WJGsEk3Qvnstmq6fa",
"object": "event",
"api_version": "2014-03-28",
"created": 1444678274,
"data": {
"object": {
"id": "ch_16vC0r1WJGsEk3Qv5rxezNQj",
"object": "charge",
"amount": 1900,
"amount_refunded": 0,
"captured": false,
"card": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek#footbole.com",
"type": "MasterCard"
},
"created": 1444678273,
"currency": "usd",
"customer": "cus_79V0ZH6qFFA4K0",
"failure_code": "card_declined",
"failure_message": "Your card was declined.",
"fraud_details": {},
"livemode": true,
"metadata": {},
"paid": false,
"refunded": false,
"refunds": [],
"source": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek#footbole.com",
"type": "MasterCard"
},
"status": "failed"
}
},
"livemode": true,
"pending_webhooks": 2,
"request": "req_79V0v7433eb9hZ",
"type": "charge.failed"
}
When I run the code locally and feed it that json, it works as expected with isAutomaticCharge and doesGettingStringWork both being false.
I'm running version 20140107 of org.json. I declare a new JSONObject for every request, so threading shouldn't be an issue. Has anyone else had issues running org.json on Google App Engine?

Categories