Array as parameter in retrofit - android

I have an issue with my parameters passing in retrofit, My problem is need to send int array ([3,1,2]) as one of the parameters in a POST method with retrofit 2, other parameters are as string. (ex: tips - "10", amount-"100", service-ids -[3,1,2]). How can send parameters like above in example.

You can use ArrayList such as:
#FormUrlEncoded
#POST("service_name")
void functionName(
#Field("yourarray[]") ArrayList<String> learning_objective_uuids, #Field("user_uuids[]") ArrayList<String> user_uuids, #Field("note") String note,
Callback<CallBackClass> callback
);
You can follow this link.
Or you could use JSONObject like so:
#POST("demo/rest/V1/customer")
Call<RegisterEntity> customerRegis(#Body JsonObject registrationData);
registrationData:
private static JsonObject generateRegistrationRequest() {
JSONObject jsonObject = new JSONObject();
try {
JSONObject subJsonObject = new JSONObject();
subJsonObject.put("email", "abc#xyz.com");
subJsonObject.put("firstname", "abc");
subJsonObject.put("lastname", "xyz");
jsonObject.put("customer", subJsonObject);
jsonObject.put("password", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
JsonObject gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString());
return gsonObject;
}

You can define an object reflecting the structure of the POST body:
#POST("/pathtopostendpoint")
Call<ResponseObject> postFunction(#Body final RequestBody body);
with your RequestBody being defined as following (if you use the GSON converter, tweak the naming of the field with #SerializedName):
class RequestBody {
String tips;
String amount;
int[] serviceIds;
RequestBody(final String tips, final amount String, final int[] serviceIds) {
this.tips = tips;
this.amount = amount;
this.serviceIds = serviceIds;
}
}
and build the request call like that:
final Call<ResponseObject> call = retrofitService.postFunction(
new RequestBody("10", "100", new int[]{ 3, 1, 2 })
);

Related

Android Volley send Array as a param along with String

I am using Volley to send data to the server, Here I am unable to find the way to send both String and Array at a time in a single request.
I can send the array like:
Map<String, List<String>> jsonParams = new HashMap<>();
jsonParams.put("names", my_names_list);
And also I can send String like:
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("user_id", userId);
but how to send both at a time?
like:
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("user_id", userId);
jsonParams.put("names", my_names_list); // here it is expecting String but I want to send array of strings to server
the expected JSON request should be like:
{
"user_id": "1",
"names" : ["abc, "cdf", "efg"]
}
I think you can merge the string and array into a single json and then send the json to the server.Example
public class Member
{
private String name;
private List<String> skills;
//getter and setter at lower
}
Use the GSON library for make this model class to json.
Member mem = createjsonobject();
Gson gson=new Gson();
String json=gson.toJson(mem);
//Pass this json to the server and at server side you can seperate the string and array
private static Member createjsonObject()
{
Member member= new Member();
member.setName("Rishabh");
List<String> skill=new ArrayList<>();
skill.add("Java");
skill.add("C#");
skill.add("Android");
member.setSkills(skill);
return member;
}
I solved my problem like this-
protected Map<String, String> getParams() throws AuthFailureError {
JSONArray words_ar = new JSONArray();
for(int i=0;i<exercise.getWord_list().size();i++){
JSONObject word_ob = new JSONObject();
try {
word_ob.put("id",(i+1)+"");
word_ob.put("learn",exercise.getWord_list().get(i).getLearn_str());
word_ob.put("native",exercise.getWord_list().get(i).getNative_str());
words_ar.put(word_ob);
} catch (JSONException e) {
e.printStackTrace();
}
}
Map<String, String> params = new HashMap<>();
params.put("user", prefs.getUserId()+"");
params.put("title", exercise.getTitle());
params.put("words", words_ar+"");
return params;
}
Try using custom JSONObject. For your above example request, you can create a JSON object as below
try {
String[] names = {"abc", "cdf", "efg"};
String userId = "user_id";
JSONArray jsonArray = new JSONArray();
for(String n : names) {
jsonArray.put(n);
}
JSONObject jsonParams = new JSONObject();
jsonParams.put("names", jsonArray);
jsonParams.put("userId", userId);
} catch (JSONException e) {
e.printStackTrace();
}
try this one ; put the names in array than:
for(int i = 0;i<yourArrayLength;i++){
params.put("names"+i, my_names_list[i]);
}
hope it will help

create jsonArray with GsonBuilder or Gson

I want to send my ArrayList<Orto> listOrtowith json to my server. Here is my code
String url = serverUrl + "addOrto1212"; //tırnak içi addOrto olacak
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
try{
JSONObject json = new JSONObject();
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(listOrto).getAsJsonArray();
json.put("list",myCustomArray);
Log.d("******************json",json.toString());
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
client.execute(post);
}catch(Exception e){
//
}
Let see Logcat;
03-30 09:24:18.655 21698-22331/com.emato.microorthodontist D/******************json: {"macid":"C9:3F:C1:B1:6F:1F","list":"[{\"date\":\"2016\/03\/30\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":31,\"dest\":0,\"melvalue\":11},{\"date\":\"2016\/03\/29\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":16,\"dest\":0,\"melvalue\":95},{\"date\":\"2016\/03\/28\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":17,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/27\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":18,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/26\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":19,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/25\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":20,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/24\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":21,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/23\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":22,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/22\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":23,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/21\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":24,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/20\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":25,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/19\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":26,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/18\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":27,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/17\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":28,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/16\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":29,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/15\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":30,\"dest\":0,\"melvalue\":0}]"}
"list" is return me one String by my listorto but I want jsonArray. Where is my mistake please help..
you can create POJO classes to represent the data you are working with, ex:
public class MyData {
private String macid;
private ArrayList<MyListItem> myList= new ArrayList<MyListItem>();
// create setters and getters
}
public class MyListItem {
private String date;
private String mac;
private Integer id;
private Integer dest;
private Integer melvalue;
// create setters and getters
}
then use GSON to convert to and from JSON:
populate data objects...
MyData mydata = new MyData();
mydata.setMacid("some:mac:id");
MyListItem item = new MyListItem();
//item .set ... set other values for the item
mydata.getMyList().add(item);//add as many items as you want
Create an instance of Gson:
Gson gson = new Gson();
1- To Json:
//from object to json string
String mydataAsJson = gson.toJson(mydata, MyData.class);
2- From Json:
//from json string to object
String jsonStr = getJsonFromServer();
MyData mydata2 = gson.fromJson(jsonStr, MyData.class);

Deserializing an object that contains a single list with gson

I have the following json I want to deserialize:
{
"locations": [{
"id": 17,
"account_id": 11,
"name": "The Haunted Lexington",
"radius": 100
}]
}
(In this particular instance, there's only one Location, but there can be many).
I deserialize this using Gson with the following code:
Gson gson = new GsonBuilder().create();
LocationList ll = gson.fromJson(jsonString, LocationList.class);
I have the following classes defined:
public class Location {
#SerializedName("id")
private long mId;
#SerializedName("account_id")
private long mAccountId;
#SerializedName("name")
private String mName;
#SerializedName("radius")
private int mRadius;
public long getId() {
return mId;
}
public String getName() {
return mName;
}
}
and:
public class LocationList {
#SerializedName("locations")
private List<Location> mLocations;
}
The thing is, I have a bunch of these "dummy" classes that contain a single object that's a list of other objects (e.g. UserList, MessageList, etc...)
What I'd like to do is have the above json parsed somehow so I can skip defining the intermediate class definition of LocationList, like so:
Gson gson = new GsonBuilder().create();
// Use the same json as above, but skip defining the superfluous "LocationList" class
List<Location> ll = gson.fromJson(jsonString, "locations", ArrayList<Location>.class);
Is there a way I can do this, perhaps by providing a custom deserializer?
I faced a similar problem not long ago, and solved it like this
// Parse the JSON response.
JSONArray jsonArray = new JSONArray(response);
List<Location> locations = new ArrayList<Location>();
/*
* Create a Location object for every JSONObject in the response,
* and add it to the list.
*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Location location = new Gson().fromJson(jsonObject.toString(),
Location.class);
locations.add(location);
The approach here is to loop over every Location in the locations array in the JSON, extracting them one by one and then adding them to a list.
The JSON I worked with had a list as root object, so you probably can't use this JSONArray jsonArray = new JSONArray(response);. Something like this might better suit your situation
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray locationsJsonArray = jsonObject.get("locations");
I have not tested these last 2 lines, but I think you get the idea.
I hope you can use this to solve your problem.
I'm currently using a simple method to achive your goal:
private static <T> List<T> getList(final String jsonVal, final String listTag, T t) {
try {
JsonObject jsonObject = (JsonObject)(new JsonParser()).parse(jsonVal); // root JsonObject. i.e. "locations"
JsonArray jsonArray = (JsonArray)jsonObject.get(listTag);
Gson gson = new GsonBuilder().create();
List<T> list = gson.fromJson(jsonArray, new TypeToken<List<T>>() {}.getType());
return list;
} catch (Exception e) {
throw new IllegalArgumentException("Unexpected json structure!", e);
}
}
Example usage:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
String jsonString = "{\"locations\":[{\"id\":17,\"account_id\":11,\"name\":\"The Haunted Lexington\",\"radius\":100}]}";
List<Location> list = getList(jsonString, "locations", new Location());
This method should be used for your orther classes, such as:
List<User> userList = getList(jsonString, "users", new User());
List<Message> messageList = getList(jsonString, "messages", new Message());

Generate JSONObject dynamically in android

I want to generate the following form
{
"dt": {
"DocumentElement": [
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "dfsfdsfd"
},
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "Chintan"
}
]
}
}
I have one arraylist which is dynamically filled with data and i also want the form in terms of dynamic. Here is my code:
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
}
DocumentElementobj.put( "DocumentElement", req );
System.out.println("Final "+DocumentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
It outputs:
Final {"DocumentElement":[]}
EDIT
Thanks to all your response. As per you all responce i make code like below
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObjdt = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", OnLineApplication.mParserResults.get(i).getCompanyId());
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
DocumentElementobj.put( "DocumentElement", req );
reqObjdt.put("dt", DocumentElementobj);
System.out.println("Final "+reqObjdt.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I get foramt which i want but in final string i get sequeence like below
{"dt":
{"DocumentElement":
[
{"Answer": "The Claims Representatives have a small role in return to work.","Question":"Return-to-Work Claim Issues. Please check the statement that best applies.","CompanyID":"8"},
{"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}}
it comes Answer first in sequence but i want to CompanyID first so what is issue in that?
You forgot to add JSONObject reqObj into JSONArray req. like req.put(reqObj);.
Modify your code block from for loop like
JSONObject reqObj = new JSONObject(); // Move inside the loop
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj); // ADDED HERE
You don't add the reqObj to req.
Do req.put(reqObj)
JSONObject documentElementobj = new JSONObject();
JSONArray req = new JSONArray();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
documentElementobj.put( "documentElement", req );
System.out.println("Final "+ documentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Also, it is better to make your variables begin with a lowercase letter, usually.
One more thing, using a debugger will be effective in this case.
There is a very good Google Libray called gson which help you to create Json Object or Parse Json Object with very ease.
You need to add gson.jar file in your project.
For More details go through the below link.
https://sites.google.com/site/gson/gson-user-guide
Edited Answer:-
public class DocumentElement {
#Expose
private String CompanyID;
#Expose
private String Question;
#Expose
private String Answer;
public DocumentElement(String CompanyID, String Question, String Answer) {
this.CompanyID = CompanyID;
this.Question = Question;
this.Answer = Answer;
}
public String getCompanyID() {
return CompanyID;
}
public String getQuestion() {
return Question;
}
public String getAnswer() {
return Answer;
}
}
public class Data {
#Expose
private ArrayList<DocumentElement> DocumentElement;
public ArrayList<DocumentElement> getDocumentElement() {
return DocumentElement;
}
public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) {
this.DocumentElement = DocumentElement;
}
}
public class ParentData {
#Expose
private Data dt;
public Data getDt() {
return dt;
}
public void setDt(Data dt) {
this.dt = dt;
}
}
And used like this to create JsonObject by help of gson.jar
ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>();
DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit");
DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta");
doc.add(doc1);
doc.add(doc2);
Data data=new Data();
data.setDocumentElement(doc);
ParentData parent=new ParentData();
parent.setDt(data);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonObj = gson.toJson(parent);
System.out.println("createdJson:---"+jsonObj);
The Result are
{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}}
Hope this will help you.
Use this code to fullfill your answer :
JSONObject jObj = new JSONObject("Your web Response");
JSONObject jObj1 = jObj.getJSONObject("dt");
JSONArray item = jObj.getJSONArray("DocumentElement");
for (int i = 0; i < item.length(); i++)
{
jObj_data = (JSONObject) item.get(i);
reqObj.put("CompanyID", jObj_data.getString("CompanyID"));
reqObj.put("Question",jObj_data.getString("Question"));
reqObj.put("Answer",jObj_data.getString("Answer"));
}

convert ArrayList<MyCustomClass> to JSONArray

I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.
UPDATE - SOLUTION
Here is what I ended up doing to solve the issue.
Object in ArrayList:
public class ListItem {
private long _masterId;
private String _name;
private long _category;
public ListItem(long masterId, String name, long category) {
_masterId = masterId;
_name = name;
_category = category;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Id", _masterId);
obj.put("Name", _name);
obj.put("Category", _category);
} catch (JSONException e) {
trace("DefaultListItem.toString JSONException: "+e.getMessage());
}
return obj;
}
}
Here is how I converted it:
ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
jsonArray.put(myCustomList.get(i).getJSONObject());
}
And the output:
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
References:
jsonarray constructor:
http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
collection:
http://developer.android.com/reference/java/util/Collection.html
Use Gson library to convert ArrayList to JsonArray.
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:
Gson gson = new Gson();
String listString = gson.toJson(
targetList,
new TypeToken<ArrayList<targetListItem>>() {}.getType());
JSONArray jsonArray = new JSONArray(listString);
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {
JSONObject jResult = new JSONObject();// main object
JSONArray jArray = new JSONArray();// /ItemDetail jsonArray
for (int i = 0; i < list.size(); i++) {
JSONObject jGroup = new JSONObject();// /sub Object
try {
jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
jGroup.put("ID", list.get(i).get("id"));
jGroup.put("Name", list.get(i).get("name"));
jGroup.put("Category", list.get(i).get("category"));
jArray.put(jGroup);
// /itemDetail Name is JsonArray Name
jResult.put("itemDetail", jArray);
return jResult;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
With kotlin and Gson we can do it more easily:
First, add Gson dependency:
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
Create a separate kotlin file, add the following methods
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
fun <T> Gson.convertToJsonString(t: T): String {
return toJson(t).toString()
}
fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
return try {
fromJson(jsonString, cls)
} catch (e: Exception) {
null
}
}
inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)
Note: Do not add declare class, just add these methods, everything will work fine.
Now to call:
create a reference of gson:
val gson=Gson()
To convert array to json string, call:
val jsonString=gson.convertToJsonString(arrayList)
To get array from json string, call:
val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)
To convert a model to json string, call:
val jsonString=gson.convertToJsonString(model)
To convert json string to model, call:
val model=gson.convertToModel(jsonString, YourModelClassName::class.java)
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList to JsonArray
JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better ..
Hope this helps.
Cheers. :D
Here is a solution with jackson:
You could use the ObjectMapper to receive a JSON String and then convert the string to a JSONArray.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
List<CustomObject> myList = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(myList);
JSONArray jsonArray = new JSONArray(jsonString);
Improving on OP's answer when there are a lot of fields.
could cut down some code with field enumeration ... ( but know that reflection is slower.)
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
Field[] fields = ListItem.class.getDeclaredFields();
for (Field f : fields) {
try {
obj.put(f.getName(), f.get(ListItem.this));
} catch (JSONException | IllegalAccessException e) {
}
}
return obj;
}

Categories

Resources