How to get string and hashmap mixed value inside a hashmap - android

I'm using volley and trying to make request to API that I'm working on. Json Request should be like this format.
{
"name": "API name",
"param":{
"email": "user#mail.com",
"password": "password"
}
}
I've tried to use hashmap but I don't know how to put
<string string>
<string, hashmap>
this is getting complicated.
Now, how should I put these values in hashmap and convert it to JSONObject and send request to server.
If this is not the way it should be done, then what should I use instead?

HahMap can not be used for JSON serialization, I suggest you to use org.json (https://mvnrepository.com/artifact/org.json/json)
Ex:
JSONObject jsonObj = new JSONObject();
JSONObject param = new JSONObject();
param.put("email","blhablah");
param.put("password","blhablah");
jsonObj.put("name", "apiName");
jsonObj.put("param", param);
System.out.println(jsonObj.toString());
This will give you the json, like follwoing :
{"param":{"password":"blhablah","email":"blhablah"},"name":"apiName"}

Related

JSON Array with RequestParams in Android Asynchronous Http Client

I have trouble to send a JSON POST Request to my server.
My server accept a POST with application/json as type and an example would be like this:
{
"name": "Group4",
"users": [
{"email": "user#example.org"},
{"email": "user2#example.org"},
]
}
If I send this by a REST client I get 200 OK as response, everything fine.
My Android client uses the Android Async HTTP Library (http://loopj.com/android-async-http/) and a documentation to the RequestParams class is here https://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
RequestParams params = new RequestParams();
String userName = getUserName();
List<String> userList = getUserList();
params.put("name", userName);
JSONArray users = new JSONArray();
for(String user : userList) {
JSONObject obj = new JSONObject();
try {
obj.put("email", user);
} catch (JSONException e) {
// ...
}
users.put(obj);
}
params.put("users", users);
I thought this will create exactly a JSON like my example. I don't know if I have the possibility to get a JSON string of this RequestParams. I only can access the parameter as a String:
name=Test&users=[{"email":"user#example.org"}, {"email":"user2#example.org"}]
My server don't even accept the request and fails directly with the error:
AttributeError: 'unicode' object has no attribute 'iteritems'
The problem has to be at the point where I create the RequestParams. Can someone tell me what is wrong with that? I thought I have to create an array with name "users" and then add objects in it with key-value items.
Just put List<> to your RequestParams. Here is the example:
RequestParams params = new RequestParams();
List<String> list = new ArrayList<String>(); // Ordered collection
list.add("Java");
list.add("C");
params.put("languages", list);
//above code will generate url params: "languages[0]=Java&languages[1]=C"
So you don't need to add it manually using Loop sequence.
See the docs here
Will recommend to use Volley for Async calls in Android https://developer.android.com/training/volley/index.html

How to post array in retrofit android

How can I post following parameter in retrofit through post method ?
"params":{"body": {
"learning_objective_uuids": [
"ED4FE2BB2008FDA9C8133FF462959C0968FAB98C4D1DB8F2"
],
"note": "FasfAFSASFASDF",
"user_uuids": [
"EDF8B7EC20005ACC5C40FF7D6E988801F5BAD83CBBCDB97F",
"EDF8F78F2000569C64101F244AA20C0070D2A7FCB1939E19"
]
}
}
} }
#FormUrlEncoded
#POST("service_name")
void functionName(
#FieldMap Map<String, String> learning_objective_uuids, #FieldMap Map<String, String> user_uuids, #Field("note") String note,
Callback<CallBackClass> callback
);
Better solution : Use arraylist.. Reference link : johnsonsu
#FormUrlEncoded
#POST("service_name")
void functionName(
#Field("learning_objective_uuids[]") ArrayList<String> learning_objective_uuids, #Field("user_uuids[]") ArrayList<String> user_uuids, #Field("note") String note,
Callback<CallBackClass> callback
);
see this example where i need to pass registration fields data as json request
#POST("magento2apidemo/rest/V1/customers")
Call<RegisterEntity> customerRegistration(#Body JsonObject registrationData);
here i have created registrationData is
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;
}
As of today, running the Retrofit implementation 'com.squareup.retrofit2:retrofit:2.1.0'
This works perfectly...
#FormUrlEncoded
#POST("index.php?action=item")
Call<Reply> updateManyItem(#Header("Authorization") String auth_token, #Field("items[]") List<Integer> items, #Field("method") String method);
You can disregard the #Header and #Field("method") .... the main piece is #Field("items[]") List<Integer> items
This is what allows you to send the items. On the API side I am simply looking for an array of integers and this works perfectly.
Go to this site : JSON Schema 2 POJO
Paste your example Json format and then
Select source type : JSON , annotation style : None
Create a POJO class then , for example your class name : MyPOJOClass
Then in your Api :
#POST("endpoint")
public Call<Void> postArray(#Body MyPOJOClass mypojoclass);
If you have headers too you can add them in parameters like that :
#Header("Accept") String accept,#Header("Content-Type") String contentType
#Edit : for your comment checkout my answer : how-to-use-gson-2-0-on-onresponse-from-retrofit-2-0
I've found a new workaround:
you can send it as a String:
#POST("CollectionPoints")
#FormUrlEncoded
Call<SomeResponse> postSomething(#Field("ids")String ids);
and send pass it like this:
Call<SomeResponse> call = service.postSomething("0","0", Arrays.toString(new int[]{53551, 53554}));
Best Regards!
Gson is the Best solution for JSON Object/Array related problems.
Here, I am sharing my easiest solution for passing array type value in retrofit API
id: ArrayList<String> //Already initilized
status: String //Already initilized
val jsonObject = JsonObject()
val toJson = Gson().toJsonTree(id) //Only one line to covert array JsonElement
jsonObject.add("id", toJson) //Add Json Element in JsonObject
jsonObject.addProperty("status", status)
API Calling using jsonObject
#POST("API_END_POINT")
fun changeStatusOfList(#Body jsonObject: JsonObject): Observable<Response<RETURN_TYPE>>
Output in Log:
{"id":["426","427"],"status":"1"}
if you want to send a list of the same name the only thing that worked for me in retrofit2 is to use #Query
#FormUrlEncoded
#POST("service_name")
void functionName(
#Query("category") List<Int> categories
);
this will send it like: https://example.com/things?category=100&category=101&category=105
the accepted answers seem not to work in Retrofit2

android: json response is just a String

I know how to access to json. Now I get a json response like that:
"2014-02-16T20:27:54+00:00"
https://openligadb-json.heroku.com/api/last_change_date_by_league_saison?league_shortcut=bl1&league_saison=2013
this is not a JSONArray and has no Name. How can I access it?
It is not json formatted data. If you need it in json, you can generate it by yourself like this :
JSONObject json = new JSONObject();
json.put("data", "2014-02-16T20:27:54+00:00" );
json.toString(); // { "data" : ""2014-02-16T20:27:54+00:00" } it is json
In other case you can work with this data as typical String. It depends on what you need to achieve.
Good luck!

How pass values into web service using JSON

I am new in android.Currently i am working in web service.But this time i got one problem.I want to pass values into server using json.The JSOn array is in this form.
{"request":{"api_key":"valid api key", "action":"register", "firstName":"aromal", "lastName":"chekavar", "email":"aromal#mstcochin.com", "address":"test address", "city":"test city", "state":"test state", "dob":"2008-06-26", "gender":"Male", "zipCode":"123456", "pin":"1234", "deviceId":"valid device id", "gcmRegId":"111111","country":"5"
}}
Please help me..
JSONObject request = new JSONObject();
JSONObject jobj = new JSONObject();
jobj.put("api_key", valiapikey);
jobj.put("action", register);
...............................
request.put("request", jobj);
Create a JSON object(jobj here) enclosing all your parameters with their keys and then enclose it in "request" JSON object.

android json response key value, parsing

i get a JSON response from a web service:
{"CoverageSearchByLatLongResult":{"HasTransmissionAreasWithSignal":true,"SwitchOffArea":
{"OpenForVastApplications":false,"SeperateTileSetUrl":"http:\/\/myswitch.merged.stage.orchard.net.au\/geodatafiles\/SwitchOffArea\/442b8844-3c05-4548-9424-
4fdafc1f3c62\/Seperate","HASStatus":"Future","HASStatement":"<p>The Household Assistance Scheme is not yet available in this switchover area. Eligible households will be sent a letter when the scheme opens in the Sydney area.<\/p>","SwitchOffDate":"31 December 2013","Events":{"MaximumProximity":6.864859435168742,"Items":[{"Name":"Test Event","Time":"Time","Url":"","Date":"Date","Address":"19a Boundary Street, Rushcutter...
so my question is, in android java how to ask for the key: CoverageSearchByLatLongResult
in ObjC in iphone , something like this:
NSDictionary *coverageResult = [response objectForKey:#"CoverageSearchByLatLongResult"];
so basically im parsing a dictionary with a key, but that result i need to put it inside other dictionary,
[correct me if wrong, in java dictionaries are called maps?]
how to do this?
thanks a lot!
You should use the classes in the org.json package:
http://developer.android.com/reference/org/json/package-summary.html
With them you can do things like:
try {
String jsonString = "YOUR JSON CONTENT";
JSONObject obj = new JSONObject(jsonString);
JSONObject anotherObj = obj.getJSONObject("CoverageSearchByLatLongResult");
boolean bool = anotherObj.getBoolean("HasTransmissionAreasWithSignal");
JSONArray jsonArray = obj.getJSONArray("arrayKey");
int i = jsonArray.getInt(0);
} catch (JSONException e) {
e.printStackTrace();
}
Java Maps map keys to values. As an example of their use:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("string key", 1);
map.put("another key", 3);

Categories

Resources