Problem when sending jsonArray using socket.io Android - 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())

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

How parse array of arrays JSON with Retrofit?

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

How to parse a json fetched from Volley Android

Heres my code of Volley Fetching API Request How do i parse?
i wanted somethinf like : $response[0]
val sq = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
//print the response
Log.i("GoogleIO","Response is : $response")
}, Response.ErrorListener {
//Log the error
Log.i("GoogleIO","That din't work")
})
//Add the request to the RequestQueue
Volley.newRequestQueue(this).add(sq)
Lets suppose you have this json string in response
{
name: "John",
age: 31,
city: "New York"
}
you can parse this string like this
try {
JSONObject obj=new JSONObject(response);
String name=obj.getString("name");
int age=obj.getInt("age");
String city=obj.getString("city");
} catch (JSONException e) {
e.printStackTrace();
}
You can use Gson for that:
First put the dependency in your app level build.gradle file.
implementation 'com.google.code.gson:gson:2.8.6'
Then you can add this:
var gson = new Gson()
var st = gson.toJson(response)
Log.i("GoogleIO","Response is : $st")

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

How to send Array of Objects in retrofit Android?

I have an below array of objects to be passed in the service call.
[
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fc250cf2497dfe5679d1"
}
},
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff2f0cf2497dfe567c0c"
}
},
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fd700cf2e65ecf6330c6"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fefe0cf2497dfe567bee"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff690cf2497dfe567c3f"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.55e972d21170d0c2fd7d15b1"
}
}]
I am trying like below:
private String generateParkingspaceBody(final List<String> listOfsIds) {
//sids array
JSONArray sidsArray = new JSONArray();
for (String sId: listOfsIds) {
//creating sidObject and object
JSONObject sIdObject = new JSONObject();
JSONObject object = new JSONObject();
try {
sIdObject.put("sid", sId);
object.put("ParkingSpace",sIdObject);
sidsArray.put(object);
} catch (JSONException e) {
CPALog.e(TAG,e.getMessage());
}
}
return sidsArray.toString();
}
Sending this string into the service call like:
Response getNearByParkingSpaces(#Header("Authorization") String accessToken,
#Header("Content-Type") String contentType,
#Body String arrayOfSids);
But in request showing in the logact is :
"[{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}}]"
Please help me, how to send this request?
Thanks in advance.
You don't need to convert your object to a JSONArray, Retrofit will do it automatically for you.
Simply change your API method declaration to:
#Headers({
"Content-type: application/json"
})
Response getNearByParkingSpaces(#Header("Authorization") String accessToken,
#Body List<String> arrayOfSids);
I encounter same issue solve this by adding this dependencies:
implementation 'com.squareup.retrofit2:converter-scalars:$version'
There are multiple existing Retrofit converters for various data formats. You can serialize and deserialize Java objects to JSON or XML or any other data format and vice versa. Within the available converters, you’ll also find a Retrofit Scalars Converter that does the job of parsing any Java primitive to be put within the request body. Conversion applies to both directions: requests and responses.
https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body
then you can use your generateParkingspaceBody as value to post.
generateParkingspaceBody.toString() as your request body

Categories

Resources