Android: org.json.JSON.typeMismatch - java

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

Related

Error on JsonElement cannot be convert to JsonObject

so there is a jsonReqObj,
jsonReqObj = {
"postData" : {
"name":"abc",
"age": 3,
"details": {
"eyeColor":"green",
"height": "172cm",
"weight": "124lb",
}
}
}
And there is a save function that will return a string. I want to use that save function, but the input parameter for the save json should be the json inside postData.
public String save(JsonObject jsonReqObj) throw IOException {
...
return message
}
below are my code
JsonObject jsonReqPostData = jsonReqObj.get("postData")
String finalMes = save(jsonReqPostData);
But I am getting the error that
com.google.gson.JsonElement cannot be convert to com.google.gson.JsonObject.
JsonObject.get returns a JsonElement - it might be a string, or a Boolean value etc.
On option is to still call get, but cast to JsonObject:
JsonObject jsonReqPostData = (JsonObject) jsonReqObj.get("postData");
This will fail with an exception if it turns out that postData is a string etc. That's probably fine. It will return null if jsonReqObj doesn't contain a postData property at all - the cast will succeed in that case, leaving the variable jsonReqPostData with a null value.
An alternative option which is probably clearer is to call getAsJsonObject instead:
JsonObject jsonReqPostData = jsonReqObj.getAsJsonObject("postData");
I have validated your JSON file with https://jsonlint.com/ and it looks like the format is incorrect, instead of be:
jsonReqObj = {
"postData": {
"name": "abc",
"age": 3,
"details": {
"eyeColor": "green",
"height": "172cm",
"weight": "124lb",
}
}
}
Should be:
{
"postData": {
"name": "abc",
"age": 3,
"details": {
"eyeColor": "green",
"height": "172cm",
"weight": "124lb"
}
}
}
Maybe thats why you cant convert to an object
Note: I would put this as a comment instead as an answer, but i dont have enought reputation T_T

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!

Converting a normal String to JSON in java

i've been searching a lot for a way to convert a normal String, not an Array, and i'm stuck in my code. I've programmed an API that return me the following json
[{
"Id": "6d052279342d66d1ae4d4a84da0f98b80313277a3faeca4d7e822076c9dd4316",
"Names": ["/elegant_bartik"],
"Image": "alpine",
"ImageID": "sha256:3fd9065eaf02feaf94d68376da52541925650b81698c53c6824d92ff63f98353",
"Command": "/bin/sh",
"Created": 1525954440,
"Ports": [],
"Labels": {},
"State": "running",
"Status": "Up About an hour",
"HostConfig": {
"NetworkMode": "default"
},
"NetworkSettings": {
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "430ff6d43b361b0a2f45046c575862ca4785216a0242e72d145c269f3ef326df",
"EndpointID": "a7a2012d7841af6b5b76e24f57b13a5057252b511e8dbfb48e74aa1cc19e30b4",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
},
"Mounts": []
}]
The problem is, I need to put it into an JSONObject, is there any function or sequence of functions that could do that? Or do I need to break the whole String?
I've tried JSONParse, Gson(from Google) and a lot more, but none of then works.
Thanks!
The JSON you have posted is an array (denoted by []) containing a single object (denoted by {})
You will first need to parse the JSON into an array, for example (using GSON):
JsonArray arr = new Gson().fromJson(string, JsonArray.class)
And then you can access the first object in the array:
JsonElement ele = arr.get(0);
First, the json array string looks okay. you will have to read it as a jsonArray, then loop through each getting the jsonObjects.
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
I hope this helps.
That's a JSONArray. You first need to get the root json array. Then you can get the first object from that.

Django JsonResponse parsing error in Android

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.

Extracting fields from JSON fields from mongodb

I want to extract all these places mentioned in "location" field and does not want the other fields in the below json.but can't be able to extract since it is nested..Can anyone help me?
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
System.out.println("data::"+curNext.get("list.myList.location");
}
My "curNext" gives output as::
{
"_id": {
"$oid": "51ebe983e4b0d529b4df2a0e"
},
"date": {
"$date": "2013-07-21T13:31:11.000Z"
},
"lTitle": "Three held for running CISF job racket",
"list": {
"myList": [
{
"location": "Germany"
},
{
"location": "Geneva"
},
{
"location": "Paris"
}
]
},
"hash": -1535814113,
"category": "news"
}
I want my output as
Germany,Geneva,Paris
I have been in a long wait here for an answer and finally I got what I was searching for...Just noting my answer so someone else can benefit from it
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
String res=curNext.toString();
JsonElement jelement = new JsonParser().parse(res);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("list");
JsonArray jarray = jobject.getAsJsonArray("myList");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("location").getAsString();
System.out.println("all places::"+result);
}
For finding only locations you should used mongo aggregation, below query will fetch all lcoations array
db.collectionName.aggregate({
"$unwind": "$ner.nerList"
},
{
"$group": {
"_id": "$_id",
"location": {
"$push": "$ner.nerList.location"
}
}
},
{
"$project": {
"location": "$location",
"_id": 0
}
})
Unfortunately I don't know how to convert this in Java but, I find below links which helpfull to you for converting above query in java format
Mongo Java aggregation driver

Categories