How parse array of arrays JSON with Retrofit? - android

When I use retrofit, I get JsonSyntaxException : Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0] How can I parse it?
[
[
{
"resturan_name": "هتل شاه عباس",
"menu_name": "کباب سلطانی",
"food_name": "پیش غذا"
},
{
"resturan_name": "هتل شاه عباس",
"menu_name": "کباب سلطانی",
"food_name": "پیش غذا"
}
],
[
{
"resturan_name": "هتل شاه عباس",
"menu_name": "کباب سلطانی",
"food_name": "عصرانه"
},
{
"resturan_name": "هتل شاه عباس",
"menu_name": "کباب سلطانی",
"food_name": "عصرانه"
}
]
]

You have an array of array of objects. So, when you're parsing your JSON, you have to use JSONArray:
val jsonArray = JSONArray(your_json)

The json received has a list but you maybe use json object pars in rerofit
see this link for resolve
Parse JSON array response using Retrofit & Gson

Change
Call<...> getListOf....(...);
To
Call<List<...>> getListOf....(...);

Using Response Model
Make your Response Model Class like this Using Gson,
class ResponseModel : ArrayList<ResponseModel.ResponseModelSubList>(){
class ResponseModelSubList : ArrayList<ResponseModelSubList.ResponseModelSubListItem>(){
#Parcelize
data class ResponseModelSubListItem(
#SerializedName("food_name")
val foodName: String? = "",
#SerializedName("menu_name")
val menuName: String? = "",
#SerializedName("resturan_name")
val resturanName: String? = ""
) : Parcelable
}
}
Parse JSON like this,
val response = ResponseModel() // Here response is getting from retofit or other networking lib. you use.
for (i in 0 until response.size) {
val responseList = response[i]
for (j in 0 until responseList.size) {
var foodName = responseList[j].foodName
var menuName = responseList[j].menuName
var restaurantName = responseList[j].resturanName
}
}
Using Manually Parsing
val jsonArray = JSONArray(response)
for (i in 0 until jsonArray.length()){
val jsonArray1 = jsonArray.get(i) as JSONArray
for (j in 0 until jsonArray1.length()){
var jsonObj = jsonArray1.get(j) as JSONObject
var foodName = jsonObj.getString("food_name")
var menuName = jsonObj.getString("menu_name")
var restaurantName = jsonObj.getString("resturan_name")
}
}

Related

Using Kotlin to parse nested json array/object

I've read a few posts on here saying to use gson or something else.
Android Kotlin parsing nested JSON
I am planning on switching to gson later but wondering how to parse with kotlin.
JSON object:
{
"childScoresList": [
{
"child_id": "1",
"score_date": "2022-03-27",
"category_id": "1",
"category_name": "Preschool Math",
"classes": [
{
"category_name": "Preschool Math",
"class_name": "Number Blocks",
"class_id": "1",
"class_description": "Ones, Tens, Hundreds Blocks used to create given numbers.",
"skills": [
{
"skill_id": "1",
"skill_name": "Place Value",
"skill_description": "Knowing the place value of specific elements.",
"skill_score": "50"
}
]
}
]
}
]
}
Kotlin code:
val obj = JSONObject(response.toString())
val jsonArray = obj.getJSONArray("childScoresList")
for (i in 0 until jsonArray.length()) {
val categoryName = jsonArray.getJSONObject(i).getString("category_name")
}
How do I get data in class_name?
I tried various things but could not get it to work.
You must first get JSONArray from the object according to the following code and then access the class_name variable
val obj = JSONObject(js)
val jsonArray = obj.getJSONArray("childScoresList")
for (i in 0 until jsonArray.length()) {
val classes = jsonArray.getJSONObject(i).getJSONArray("classes")
for (x in 0 until classes.length()) {
val categoryName = classes.getJSONObject(x).getString("category_name")
val className = classes.getJSONObject(x).getString("class_name")
}
}

Problem when sending jsonArray using socket.io Android

When I send my JSONArray object through socket like this:
val json = JSONArray()
....
socket?.emit(EVENT, json)
server gets my message as array within array, like:
[ [ { lat: 31.476369999999996, long: 74.26562} ], 'Function0<kotlin.Unit>' ]
I want to send only this:
[ { lat: 31.476369999999996, long: 74.26562} ]
Example code to send json array using custom arraylist
var obj: JSONObject? = null
val jsonArrayLatLng = JSONArray()
for (i in 0 until list!!.size) {
obj = JSONObject()
try {
obj.put("lat", list.get(i).lat)
obj.put("long", list.get(i).lng)
} catch (e: JSONException) {
e.printStackTrace()
}
jsonArrayLatLng.put(obj)
}
val jsonObject = JSONObject()
jsonObject.put("list_key_name_here", jsonArrayLatLng)
socket?.emit(EVENT, jsonObject)
This worked
socket?.emit(EVENT, jsonArray.toTypedArray())

fetching value of specific key from json response

how can I store a specific value of a key from json response into a variable
{
"results": [
{
"name": ryan,
"roll_id": 64,
"class_id": 310,
"net_id": 95,
},
],
};
above is the json response :-
val gson = GsonBuilder().create()
val ListV = gson.fromJson(body, HomeClass::class.java)
after these 2 lines I'm totally clueless how to do it I've gone through Internet but It was hard for me to understand how to proceed further.
Your Json Structure will be
{
"results": [
{
"name": "Amiyo",
"roll_id": 1,
"class_id": 10,
"net_id": 91
},
{
....
}
]
}
Data class should be
data class HomeClass (
#SerializedName("results") val results : List<Results>
)
data class Results (
#SerializedName("name") val name : String,
#SerializedName("roll_id") val roll_id : Int,
#SerializedName("class_id") val class_id : Int,
#SerializedName("net_id") val net_id : Int
)
fromJson
val listData = gson.fromJson(jsonData, HomeClass::class.java)
Then
val totalSize = 0 until listData!!.size
if(totalSize.size>0)
{
for (i in totalSize)
{
//Your Code i==Position
}
}

Parsing API data which contain object (Klaxon) (Kotlin)

I have API response which contain object (graphic)
[
{
"code": 200,
"status": "OK",
"FirstDay": "2019-11-18",
"LastDay": "2019-11-24",
"graphic": {
"2019-11-23": [
{
"godzinaStart": "08:30",
"godzinaStop": "10:00",
"przedmiot": "Matematyka dyskretna",
"sala": "32AK8",
"nauczyciel": "xxx",
"grupy": "1K131; 1K132; 1K133; 1K134; 1K135; 2K131",
"typ": "wykład"
},
],
"2019-11-24": [
{
"godzinaStart": "08:30",
"godzinaStop": "10:00",
"przedmiot": "Podstawy informatyki",
"sala": "308K",
"nauczyciel": "xxx",
"grupy": "1K131",
"typ": "laboratorium"
},
]
}
}
]
I have to parse this JSON to object in Kotlin. So i made class with parameters
class GraphicAPIResponse(
var code: Int,
var status: String,
var errorMessage: String = "",
var FirstDay: String = "",
var LastDay: String = "",
var graphic: JsonObject? = null OR var graphic: JsonArray<Any>? = null (I tried both)
)
I'm parsing data by this function
val responeAPI = Klaxon().parseArray<GraphicAPIResponse>(response)
When graphic is JsonObiect type appliaction throw error
I/System.out: ERROR -> Unable to instantiate JsonObject with parameters []
When graphic is JsonArray<Any> type, here's error
I/System.out: ERROR -> Unable to instantiate GraphicAPIResponse with parameters [LastDay: 2019-11-24, code: 200, status: OK, graphic: java.lang.Object#aef265a, FirstDay: 2019-11-18]
I'm trying to resolve the problem from 2 hours. Can someone help me please? :(
#EDIT
Thank You #Alexey Romanov
That help
Define a type for the nested object:
class Lesson(val godzinaStart: String, val godzinaStop: String, ...)
and use it in GraphicAPIResponse:
class GraphicAPIResponse(
var code: Int,
var status: String,
var errorMessage: String = "",
var FirstDay: String = "",
var LastDay: String = "",
var graphic: Map<String, Lesson> = mapOf()
)
(though honestly, I'd expect JsonObject to work as well)

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

Categories

Resources