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
Related
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);
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")
I have one Registration Api which has error object in which it shows Errors Dynamically in Array.
This is the JsonFormat of Api :
{
"status_code": 422,
"status": "error",
"data": {
"errors": {
"password": [
"The password must be between 8 and 15 characters."
],
"mobile_no": [
"The mobile number has already been taken."
]
}
}
}
Here if a user forgot to write name then it will show username array in errors. So it changes dynamically.
My question is how I can set this type of errors in gson.I am using retrofit to call Api.
I did this in my Data class but it showing me errors.
#SerializedName("errors")
#Expose
JsonObject errorObject;
Iterator iterator=new Iterator() {
#Override
public boolean hasNext() {
Iterator keys=errorObject.keys();
if(keys.hasNext()){
}
}
#Override
public Object next() {
return null;
}
}
Please help me how can I getErrors using gson.Thank u
You can use Map to maintin the datastructure like this:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(yourErrorsArrayHere, type);
and then just use myMap.get("your_error_key") to get the particular error.
My Code - I'm trying to return the data from JSON.
JSONObject count = new JSONObject(finalJson);
JSONArray itemsArray = count.getJSONArray("Items");
JSONObject finalObject = itemsArray.getJSONObject(0);
String record = finalObject.getString("myid");
String vocabulary = finalObject.getString("vocab");
String method = finalObject.getString("method");
return record + vocabulary + method;
JSON I'm trying to parse- Count object, Items array, etc...
{
"Count":1,
"Items":[
{
"myid":{
"S":"1"
},
"vocab":{
"S":"print a line"
},
"method":{
"S":"system.out.println"
}
}
],
"ScannedCount":1
If there is a fixed schema, you can transfer the DynamoDB JSON to JSON via a mapping template on API Gateway.
Mapping Template
#set($inputRoot = $input.path('$'))
{
"items": [
#foreach($elem in $inputRoot.Items) {
"myid": "$elem.myid.S",
"vocab": "$elem.vocab.S",
"method": "$elem.method.S"
}#if($foreach.hasNext),#end
#end
]
}
Then, you can parse the JSON String from API Gateway in your Android application into an object.
Sample parsing code
public class Items {
private List<Item> items;
//getters and setters
}
public class Item {
private String myid;
private String vocab;
private String message;
//getters and setters
}
Items items;
ObjectMapper mapper = new ObjectMapper();
jsonData = .... // from API Gateway
items = mapper.readValue(jsonData, Items.class);
Also, there is better way to get those information from API Gateway's generated android SDK. In order to do so, you need to define a Model Schema and set to the method response, then once you deploy your API change this modification, you can download an android SDK for your API.
Model Schema
{
"type": "object",
"properties": {
"items": {
"type": "array",
"item": {
"properties": {
"myid": {
"type": "string"
},
"vocab": {
"type": "string"
},
"method": {
"type": "string"
}
}
}
}
}
}
You might want to read this step by step walkthrough if you want to have more detail on how to mapping response work, and
I've used gson library for parsing json response. its working well. now i got a problem .
i've got below response from webservice. the json key value is not static, it will dynamically change.
how to write a parser class to parse the below response.
Formatted JSON:
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
Use this parser class
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
If possible get a JSON response with all possible "Key" values and then get the POJO class auto build from below link:
POJO FOR GSON
It will automatically handle all the posibilities. But make sure the RESPONCE you are providing while generating the POJO should hold all the possible combinations of your Key [changing once].
HOPE THIS HELPS!!
Depending on your specification, you can make a Default Webservice response model.java which would be something like:
String success;
#SerializedName("error_msg")
String errorMessage;
#SerializedName("error_code")
String errorCode;
JsonObject data;
where the Parent of the object with dynamic keys would be the "data".
Use Gson, map the model class:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
Will edit my answer on question edit, in any way if it can help
Just a suggestion - raja, you etc. can be values for a key - name or commentsBy ? Where are you getting this response from?