JSON array coming as json object if no data in Android - android

I am getting JSON response from the API call. But in that response one of the JSONArray is coming as JSONObject if there is no data as given below. Without data : "InbuildData": null.
With data :"InbuildData": [{"value": "Yes","checkStatus":0}]. Anyone please suggest better option to identify this situation!

Not user about your confusion this is a simple case you can handle this like this in your model
#SerializedName("InbuildDataItem")
var inBuildDataItem:InbuildDataItem?=null
data class InbuildDataItem(
#SerializedName("checkStatus")
val checkStatus: Int,
#SerializedName("value")
val value: String
)
Before using check if inBuildDataItem is null or not

Related

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' error in dart

I have tried to decode a json file which is coming back from server after my request, but when i want to decode the json it show an error
here is my decode codes:
var loginJson = jsonDecode(utf8.decode(response.bodyBytes));
var model = idResponseModel(
loginJson['id'],
loginJson["fname"],
loginJson["lname"],
loginJson["nationalCode"],
loginJson["gender"],
loginJson["bornDate"],
loginJson["phoneNumber"],
loginJson["cardNumber"],
loginJson["enabled"]);
print(model.id);
and console says it happened in loginJson['id']
the id from server is some thing like this :
"id": "5de0a41e-9a6f-4b55-9567-024cd0fdbfc5"
slightly surprised by the direct use of [bodyBytes] try using the Response getter → body
String get body => _encodingForHeaders(headers).decode(bodyBytes);
in your case it should look like this:
var loginJson = jsonDecode(response.body);
var model = idResponseModel(
loginJson['id'],
loginJson["fname"],
loginJson["lname"],
loginJson["nationalCode"],
loginJson["gender"],
loginJson["bornDate"],
loginJson["phoneNumber"],
loginJson["cardNumber"],
loginJson["enabled"]);
print(model.id);
I have no way to check it now but if it works let me know
This error means that loginJson.[] expects an int, not a String. So it's possible that loginJson is actually a List, and not a Map like you expect it to be. You can check by printing loginJson.runtimeType.
Unless you'd post the whole JSON, this question is insufficient and not reproducible... because you might believe you have the response already, while trying to get data from the wrong one node (id is a string index, but it encounters an unexpected numeric index). That's exactly why your sample data and the error message do not provide the least meaning in combination.

Json Response conversion Stuff in Android

Below is the model class I am created for my json response :
data class MyModelClass(
val one: String,
val two: String,
val three: String,
val four: Int,
val tempCurrentCharge: List<CurrentCharge>,
val tempCurrentDischarge: List<CurrentDischarge>
)
Now, above you can see that I am getting Arrays of List<CurrentCharge> and List<CurrentDischarge> in my Json response as below :
"tempCurrentCharge": [
{
"temp": -600,
"cRating": 0
},
{
"temp": 0,
"cRating": 10
}
]
Now, I can successfully parse the json response and saved it in my local db (as per my need).
Now I have two feilds in my local db table, one is for CurrentCharge and another if for CurrentDischarge.
I have to save the whole json string as value in this.
Currently It saved as Object.toString() Instead I want to save the whole json string which is as shared above.
The issue is since I have created the pojo class for json parsing, Its parsing the data for tempCurrentCharge and tempCurrentDischarge automatically.
But I want to store the values of json String in it.
So, What I have done is: changed the type of both the variables as String
But then it given me type casting error as :
"BEGIN_ARRAY... found String".
So, Anyone please suggest me how can I achive storing above jsonArray as string json in my local room db field?
Thanks in Advance.
Let your data class remain as it is, the error you are receiving is justified because in the response you are getting an array while you have changed the type in your data class to a String and thus the following error
"BEGIN_ARRAY... found String".
Coming to what you need, you can simply convert it back to JSON once it is parsed and save it then. You will need Gson library and I am sure it is added to your project. If not please add it.
What next you will need is to simply do is this. I am assuming you have an object of the BatteryConfigurationDetails class
val batteryConfig = BatteryConfigurationDetails()
val tempCurrentChargeJson = Gson().toJson(batteryConfig.tempCurrentCharge)
val tempCurrentDischargeJson = Gson().toJson(batteryConfig.tempCurrentDischarge)
To convert it back you can use the following function
Gson().fromJson()
Add the following if you do not have the library already
implementation 'com.google.code.gson:gson:2.8.7'

I am not able to parse the mag and place and time as in nested class of JSON in app they all show value as null

code is present inside this link https://github.com/Pranjul120568/AndroidPracticeQuakeReport. and link to the api https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ci39540463.geojson
You have to use Response instead of Property at parsing
Problem at line number 31 :
val quake=gson.fromJson(response, Properties::class.java)
Solution:
val quake = gson.fromJson(response, Response::class.java)

Android Volley Post JSON Array with paramater and getting response in JSON Object

I am facing strange problem with Google Volley I hope some one help me out quickly. I want to send JSON array in parameter and server will give me response in JSON object. How can we achieve this?
e.g
I wanted to post this JSON array.
[
{
"name":"John",
"age":"30",
"cars":"6"
},
{
"name":"John",
"age":"30",
"car
}
]
and server will send response in JSON object format like this.
{
"status":"success",
"code":30,
}
Can someone explain to me how I can achieve this thing?. Moreover, my JSONarray consist of mobile contacts and size will be large.
You can use Map<Object, Object> where value be collection of json Element you want. You can make custom deserilizator with lib like "gson".
You should try: JSONArray arr = new JSONArray(JSON_STRING);

Android JSON fetching - No value for (value) eventhough the value exists

I have a valid json link, and I want to fetch data from it.
This is my code, for fetching data:
try {
JSONObject topicsObject = new JSONObject(getTopicsJSON);
JSONArray topics = topicsObject.getJSONArray("Topics");
for (int i = 0; i<topics.length();i++){
SuperTrenerTopic stt = new SuperTrenerTopic();
JSONObject sub_topic = topics.getJSONObject(i);
JSONObject topic = sub_topic.getJSONObject("Topic");
...
}
On the last line of code, I get ann error saying org.json.JSONException: No value for Topic.
Following screenshot shows that it is not correct, as I Log-ed the recieved JSON, and you can clearly see that in fact, there IS a "Topic" object out there:
First Log represents the first part of an entire Json responce, and the second one is the Topic object itself.
Here is another screenshot of the JSON format i took from my browser:
You can notice that "Topic" and "meta" objects are on the same hierarchy level.
I fetch "meta" object with no problem whatsoever, using the same code I would use for fetching 'Topics", but for some reason, fetching "Topics" doesn't work out.
here is the code I successfully use to fetch "meta' object:
JSONObject meta = sub_topic.getJSONObject("meta");
What could be the cause of this?
Is there something realy obvious that I'm missing out?

Categories

Resources