Kotlin - Parse JSON - android

I have a json string with 2 keys error and user. First I want to check if error is not false and get the values from user.
Here is the Json String:
{
"error": false,
"user": {
"id": 26,
"name": "Someone",
"email": "someone#gmail.com",
"aktif": 1
}
}
How can I achieve this ?

Get the JsonObject "error" first :
val errorCheck = yourjsonresult.getJSONObject("error");
Then compare to check if it was false then:
if(errorCheck.equals("false")) { // or if it wasn't false -> !errorCheck.equals("false"))
val data = yourjsonresult.getJsonObject("user"); // get the user object
val name = data?.getString("name"); // or the other items
}
The result should be:
Someone
Also, arrays starts by [ but in your case, those are json objects which starts-ends by {}.

Related

Consuming polymorphic json "data: { put_anything_here }" with Gson & Retrofit

I'm not sure if polymorphic is the right term to use so my apologies.
I'm working with the following API:
Request body:
{
"user_id": "user_id",
"command": "submit_document",
}
Response:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "documents_rejected", // This is unique for different `data`
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object with known fields and parameters
}
}
I have data classes ready for different types of data responses like:
data class PhoneData(
#SerializedName("phone_number")
val phoneNumber: String? = null,
#SerializedName("phone_status")
val phoneStatus: String? = null
)
for "screen": "phone" and the following for another screen:
data class Data(
val deepLink: String? = null
)
The problem is, at the start, I have to make the following request to retrieve the current screen:
{
"user_id": "user_id",
"command": "get_current_screen",
}
which returns a similar response as above:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "main_screen", // Different types of screen types are known.
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object but the object could contain anything depending on the `screen` type.
}
}
but the data field could contain anything depending on the screen
data class SplashScreenData(
// How do I make this data class combine all other data classes? One ugly approach is to add all the fields from different `data` classes here and use this one only.
)
I found about the RuntimeTypeAdapterFactory for polymorphic cases but am not sure how to make it work when there's no "type" like field within the data object (screen is unique but it's outside the data object).
It would be very helpful if someone has a solution or could point me in a direction.
val frameTextReceived: String = frame.readText()
val jsonObject = JsonParser.parseString(frameTextReceived).asJsonObject
val type = when (jsonObject.get("type").asString) {
TYPE_JOIN_ROOM -> JoinRoom::class.java
TYPE_GAME_MOVE -> GameMove::class.java
TYPE_DISCONNECT_REQUEST -> DisconnectRequest::class.java
else -> BaseModel::class.java
}
val payload = gson.fromJson(frameTextReceived, type)
This is my solution, here I have type parameter by which I can know in which class I have to deserialize the object but in your case you have screen parameter, you can use this.

How to GET data from single value inside JSON Object from JSON Array?

I am new to Kotlin beginner and trying to create a code to fetch data from JSON.
I'd like to fetch the data from "value" inside "forecastMaxtemp".
Here is my code. I am tried as below but not successful.
...
Response.Listener { response ->
temp.text =
response.getJSONArray (name"weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getString(name"value")
},
JSON Data
{"generalSituation":No Alarm",
"weatherForecast":[{
"forecastDate":"20211004",
"week":"Monday",
"forecastWind":"East force 4 to 5.",
"forecastWeather":"Sunny periods.",
"forecastMaxtemp":{"value":31,"unit":"C"},
"forecastMintemp":{"value":27,"unit":"C"},
...
...
]
}
Your JSON has an issue, I think this is the right format:
{
"generalSituation": "No Alarm",
"weatherForecast": [
{
"forecastDate": "20211004",
"week": "Monday",
"forecastWind": "East force 4 to 5.",
"forecastWeather": "Sunny periods.",
"forecastMaxtemp": {
"value": 31,
"unit": "C"
},
"forecastMintemp": {
"value": 27,
"unit": "C"
}
}
]
}
to get the value from "forecastMaxtemp",
val json = JSONObject("YOUR_JSON")
val obj = json.getJSONArray("weatherForecast").get(0) as JSONObject
val value = obj.getJSONObject("forecastMaxtemp").getInt("value")
{"value":31,"unit":"C"} here 31 is int, so use getInt() function.
response.getJSONArray ("weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getInt("value")
}

How To Parse Response of Multiple Types of Single Key

How To Parse Response of Multiple Types?
Key is like (suppose student_list is a key of list types when student_list is empty then it makes as a string like student_list=""), How to manage this types of response using Retrofit? I am using MVVM Model with retrofit.
My Response:
when I get Data into the List
{
"status": 200,
"data": [
{
"prod_month_total": 2989.61,
"product": "GAS"
},
{
"prod_month_total": 39566.22,
"product": "OIL"
},
{
"prod_month_total": 83912.55,
"product": "OTHER"
}
]
}
when List is Empty Then Response:
{"status":404,"data":"No result found"}
I am getting this Error:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 23 path $.data
first create the right model calss use this site http://www.jsonschema2pojo.org
than use
`if( reponce.isSucessful){
if(responce.status==200){
//code here
}
else{
// find the error
}
}else
{
//
}`

How to parse nested array insided a json object

So I made an api in laravel and it returns a response like this:
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email has already been taken."
],
"mobile": [
"The mobile has already been taken."
]
}
}
Can somebody show me how to get the specific values from errors?
You may create model representing your error json and use Gson to parse it. Here is some short example.
data class Errors(
val email: List<String>,
val phone: List<String>
)
data class YourErrorModel(
val message: String,
val errors: Errors
)
fun parseError(response: Response<*>): YourErrorModel? {
val errorBody = response.errorBody()?.string() ?: return null //No error body present
return Gson().fromJson(errorBody, YourErrorModel::class.java)
}
Also don't forget to handle nullable types in your response. And i suggest you to return just string, not array if that is exact error for field.
How about this :
JSONObject errorObject = yourJSONObject.optJSONObject("errors");
if (errorObject != null){
JSONArray emailMsgArray = errorObject.getJSONArray("email");
JSONArray mobileMsgArray = errorObject.getJSONArray("mobile");
String emailMsg= emailMsgArray.getString(0);
String mobileMsg= mobileMsgArray .getString(0);
}

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));

Categories

Resources