How to call JSONObject in Retrofit api calls? - android

Example: My input is
"items":[{
"service_id":"1",
"service_description":"description here",
"service_quantity":1,
"service_uom":"number",
"service_price":"10000",
"service_total":"10000",
"service_taxid":1,
"service_taxvalue":"10"
},
{
"service_id":"2",
"service_description":"description here",
"service_quantity":1,
"service_uom":"number",
"service_price":"10000",
"service_total":"10000",
"service_taxid":1,
"service_taxvalue":"10"
}]
I declared like: API Call-
#FormUrlEncoded
#POST("URL")
Observable<SampleResponse> generateInvoice(#Field("items") JSONArray params);
Declaration:
JSONObject service1 = new JSONObject();
try {
service1.put("service_id", id);
service1.put("service_description", Desc);
service1.put("service_quantity", Integer.valueOf(Qty));
service1.put("service_uom", "number");
service1.put("service_price", Amt);
service1.put("service_total", GAmt);
service1.put("service_taxid", 1);
service1.put("service_taxvalue", 5);
Log.d("jsonobject created",""+service1);
}
catch (JSONException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray().put(service1);
presenter.generateInvoice(array);
Error at backend: '{\"service_id\":3,\"service_description\":\"Mobile
Application\",\"service_quantity\":5,\"service_uom\":\"number\",\"service_price\":\"650\",\"service_total\":\"3640\",\"service_taxid\":1,\"service_taxvalue\":5}';

You need to make 2 pojo class based on your request.
class RequestClass {
#SerializedName("items")
#Expose
var items: List<Item> = arrayListOf()
}
Item class will contains all the string fields that you have in your request, and in retrofit api you need to pass RequestClass like below. and remove the #FormUrlEncoded
#POST("URL")
Observable<SampleResponse> generateInvoice(#Body RequestClass requestClass);

Related

how to get json by retrofit if serialize is date

I have a Json like this
"data": {
"2020-05-01": {
"tanggal": "Jumat, 01\/05\/2020",
"subuh": "05:05",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:51"
},
"2020-05-02": {
"tanggal": "Sabtu, 02\/05\/2020",
"subuh": "05:04",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:52"
}
}
how can I get the Json, If the object is Date but I must have to use retrofit
Thanks for your help.
Try to use a Map:
class Data {
Map<String, MyObject> firstData;
Map<String, MyObject> secondData;
}
Where MyObject is:
class MyObject {
String tanggal;
String subuh;
String dzuhur;
String ashar;
String maghrib;
String isya;
}

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

Retrofit List of object assigns null to data

This is how my JSON response looks
[
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
},
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
}
]
this is my retrofit interface call
#GET("/api/GPS")
#Headers({
"Accept: application/json"
})
Call<List<UserResponse>> search(#Query("search") String search,
#Header("Authorization") String auth);
Pojo Class
public class UserResponse {
#SerializedName("Id")
int id;
#SerializedName("UserName")
String phName;
#SerializedName("Longitude")
int lon;
#SerializedName("Latitude")
int lat;
#SerializedName("ApplicationUserId")
String appUserId;
//getters and setters
}
Retrofit declaration
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(PerformLogin.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Getting data and using it
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
Call<List<UserResponse>> call = apiService.search(query,"Bearer "+token);
call.enqueue(new Callback<List<UserResponse>>() {
#Override
public void onResponse(Call<List<UserResponse>> call, Response<List<UserResponse>> response) {
List<UserResponse> userList = response.body();
Log.w("My App", response.message());
for (int i = 0; i <userList.size() ; i++) {
Log.w("My App", userList.get(i).getPhName()+""+i);
}
//mAdapter = new MyAdapter(getContext(),userList);
//mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<List<UserResponse>> call, Throwable t) {
Log.w("My App", t.getMessage());
}
});
my response
W/My App: OK
W/My App: null 0
W/My App: null 1
W/My App: null 2
W/My App: null 3
In this case I am suppose to receive four result from the search and the names are giving me null.
Is there anything I am doing wrong or a better solution to this?
You are using wrong serialize name. You are trying to assign value from node UserName to phName, which is not available. So, you are getting null.
Change
#SerializedName("UserName")
String phName;
with
#SerializedName("PhName") // change this
String phName;
Also, #SerializedName("Id") should be #SerializedName("id"). It's case sensitive.
Your SerializedName fields and the JSON fields don't match.
JSON: id -> GSON: Id
JSON: PhName -> GSON: UserName
Those two don't add up. You have to alter your annotations accordingly:
#SerializedName("id")
int id;
#SerializedName("PhName")
String phName;

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

Read JSONArray from JSONObject using GSON Android

How to read a JSONArray from a JSONObject using GSON.
I am trying to read this JSON String:
String str = { "text" : [
{
"id": 1,
"msg":"abc"
},
{
"id": 2,
"msg":"xyz"
},
{
"id": 3,
"msg":"pqr"
}
] }
The class is:
Class A {
int id;
String msg;
// And setters and getters
}
This code does not work:
class Test {
A [] text;
}
Test t = gson.fromJson(response, Test.class);
Also
class Test {
ArrayList<A> text = new ArrayList<A>();
}
Test t = gson.fromJson(response, Test.class);
How else can i read the string using my Test class?
Please help...
Update your class
public class A {
#SerializedName("id")
int id;
#SerializedName("msg")
String msg;
// And All setter and getter
}
The values given as "JSON String" are values to initiate the A class. And they are an array of As. What might work is
A[] t = gson.fromJson(response, A[].class);
Deserializing arrays is described in the manual, 5.4 Array Examples.

Categories

Resources