How to get value of HttpResponseMessage like HttpStatusCode Using Koush ION - android

Here is How I returned HttpResponseMessage from my ASP.net server like
return Request.CreateResponse(HttpStatusCode.OK,"some string");
And I have accessed the returned response in android with Kaush ION like this
Ion.with(LoginActivity.this)
.load("--URL TO POST--")
.setJsonObjectBody(jsonToSubmit)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
//I want to access header information here
}
Inside onCompleted Method I can easily access HttpStatusCode like
int code = result.getHeaders().code();
OR
String statusCode = result.getHeaders().message();
Now My Question is :
How can I get that "some string" which was sent in HttpResponseMessage with HttpStatusCode ?

----Here is the solution-----
Create a model class StringMsg.cs
public class StringMsg
{
public string Message { get; set; }
}
If you want to send string message and want to retrieve that send it like
StringMsg str = new StringMsg();
str.Message = "some string";
return Request.CreateResponse(HttpStatusCode.OK, str);
Finally, Retrieve The String in onCompleted Method like this
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
JsonObject result1 = result.getResult();
String myResult = result1.get("Message"); // Result
}

Related

How i can can parse JSON Object ? just a simple object I am new [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
I want to get string values on this one
{"response":"success","Message":"Product Created Successfully"}
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject JO = response.getJSONObject();
String respond = JO.getString("response");
String message = JO.getString("Message");
Toast.makeText(MainActivity.this, respon + message,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
you must write this code in your try{...} block
String respond = response.getString("response");
String message = response.getString("Message");
Toast.makeText(MainActivity.this, respond + message,Toast.LENGTH_SHORT).show();
As a new programmer I recommend you:
A. Read some how you work with Jason.
http://www.vogella.com/tutorials/AndroidJSON/article.html
B. Use the Jason library to make it easy for you down the road.
I'll give you an example of the right use for your needs now.
Build a class that fits your json:
public class MyObject {
private String response;
private String Message;
public MyObject() {
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
}
Add Gson library to your project:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Sync your project and now you can cast your json easily to class object:
String json = "{response:success,Message\":Product Created Successfully}";
MyObject myObject = new Gson().fromJson(json, MyObject.class);
String a = myObject.getResponse();
String b = myObject.getMessage();

How to convert retrofit response into json object

I just wanted to know that how could I convert this retrofit library response which is actually a JSON response to JSON object so I could use this in my android app to do something because I can not do anything with response in the buffered reader.
public void getMe(){
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
myApi api = adapter.create(myApi.class);
api.sendme(
userEmail,
rs,
Team1,
Team2,
new retrofit.Callback<retrofit.client.Response>() {
#Override
public void success(retrofit.client.Response result, retrofit.client.Response response) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
if (!output.equals("")) {
output = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
// loading.dismiss();
Toast.makeText(Leaderboard.this, "", Toast.LENGTH_LONG).show();
}
}
);
}
here get me is sending post response to the server
public interface myApi {
#FormUrlEncoded
#POST("/myleaderboard.php")
void sendme(
#Field("userEmail") String userEmail,
#Field("rs") String rs,
#Field("team1") String team1,
#Field("team2") String team2,
Callback<Response> callback);
}
I m getting JSON response and I have to store that in my android code somehow whether that be using JSON object or anything else if possible.
please help me with this
Just change the myAPi code to
public interface myApi {
#FormUrlEncoded
#POST("/myleaderboard.php")
void sendme(
#Field("userEmail") String userEmail,
#Field("rs") String rs,
#Field("team1") String team1,
#Field("team2") String team2,
Callback<JsonObject> callback);
}
it will return JsonObject directly
Use GsonConverterFactory to convert incoming json into model/pojo class
implementation 'com.squareup.retrofit2:converter-gson:LATEST_VERSION'
Please go through following links
Retrofit Library Tutorial
Consuming-APIs-with-Retrofit
Use this link to convert your JSON into POJO with select options as selected in image below [http://www.jsonschema2pojo.org/
You will get a POJO class for your response like this
public class Result {
#SerializedName("id")
#Expose
private Integer id;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
then and use interface like this:
#FormUrlEncoded
#POST("/api/level")
Call<Result> checkLevel(#Field("id") int id);
add the dependencies
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'
and call like this:
Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
to get the response in JSON don't use addConverterFactory(GsonConverterFactory.create()) from Retrofit.

How to get nested string from JsonElement?

I am getting JSonElement as Response from retrofit and I want to get only a string from it's object, so how can I achieve it ? I have browsed over too many sites but nothing found
RestClient.get().getVoterSlip("Bearer " + Constants.ACCESS_TOKEN, new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement , Response response) {
// want to get a string here from jsonElement
}
#Override
public void failure(RetrofitError error) {
}
});
I do not want to cast it with model class.
If you could share ur Json response, we could help you better.
But first get the JsonObject and then get the string that you want.
for example,
JSONObject jsonObj = array.getJSONObject(0); String theString =
jsonObj.getString("NeededString");
Refer https://developer.android.com/reference/org/json/JSONObject.html

Getting simple JSON object response using Retrofit library

I have a web query with JSON response as:
{
"status":true,
"result":
{
"id":"1",
"name":"ABC 1",
"email":"info#ABc.dcom",
"password":"123456",
"status":false,
"created":"0000-00-00 00:00:00"
},
"message":"Login successfully"
}
I am using the following code for:
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<JSONObject> callback);
In Debugger the query made by the Retrofit library is correct, however I get an empty JSON in response.
ApiManager.getInstance().mUrlManager.login(
email.getText().toString().trim(),
password.getText().toString().trim(),
new Callback<JSONObject>()
{
#Override
public void success(JSONObject jsonObj, Response response)
{
mDialog.dismiss();
Simply use JsonElement insted of JSONobject. Like:
#GET("/stockers/login")
Call<JsonElement> getLogin(
#Query("email") String email,
#Query("password") String password
);
The answers seam kinda old and for Retrofit 1, if you are using Retrofit 2 and don't want to use a converter you have to use ResponseBody.
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<ResponseBody> callback);
And then in your callback in the onResponse method call string on the body and create a JSONObject from it.
if(response.isSuccessful())
JSONObject json = new JSONObject(response.body().string());
Instead of Callback with JSONObject class, you could use the Retrofit basic callback which use the Response class and then, once you get the response, you had to create the JSONObject from it.
See this:
https://stackoverflow.com/a/30870326/2037304
Otherwise you can create your own model class to handle the response.
First the Result class:
public class Result {
public int id;
public String name;
public String email;
public String password;
public boolean status;
public Date created;
}
And then your response class to use with Retrofit
public class MyResponse {
public boolean status;
public Result result;
public String message;
}
Now you can call:
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<MyResponse> callback);
You can create custom factory like belowe or copy it from here :
https://github.com/marcinOz/Retrofit2JSONConverterFactory
public class JSONConverterFactory extends Converter.Factory {
public static JSONConverterFactory create() {
return new JSONConverterFactory();
}
private JSONConverterFactory() {
}
#Override public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (type == JSONObject.class
|| type == JSONArray.class) {
return JSONRequestBodyConverter.INSTANCE;
}
return null;
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (type == JSONObject.class) {
return JSONResponseBodyConverters.JSONObjectResponseBodyConverter.INSTANCE;
}
if (type == JSONArray.class) {
return JSONResponseBodyConverters.JSONArrayResponseBodyConverter.INSTANCE;
}
return null;
}
}
public class JSONRequestBodyConverter<T> implements Converter<T, RequestBody> {
static final JSONRequestBodyConverter<Object> INSTANCE = new JSONRequestBodyConverter<>();
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain; charset=UTF-8");
private JSONRequestBodyConverter() {
}
#Override public RequestBody convert(T value) throws IOException {
return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
}
}
public class JSONResponseBodyConverters {
private JSONResponseBodyConverters() {}
static final class JSONObjectResponseBodyConverter implements Converter<ResponseBody, JSONObject> {
static final JSONObjectResponseBodyConverter INSTANCE = new JSONObjectResponseBodyConverter();
#Override public JSONObject convert(ResponseBody value) throws IOException {
try {
return new JSONObject(value.string());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
static final class JSONArrayResponseBodyConverter implements Converter<ResponseBody, JSONArray> {
static final JSONArrayResponseBodyConverter INSTANCE = new JSONArrayResponseBodyConverter();
#Override public JSONArray convert(ResponseBody value) throws IOException {
try {
return new JSONArray(value.string());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
try this instead :
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<Response> callback); // set the callback generic parameter to Response
ApiManager.getInstance().mUrlManager.login(
email.getText().toString().trim(),
password.getText().toString().trim(),
new Callback<Response>()
{
#Override
public void success(Response response, Response response1)
{
String json = response.getBody();
try {
JSONObject jsonObj = new JSONObject(json);
} catch(JSONException e) {
}
alog.dismiss();
Just define the type of the object you want to get as a String as com.google.gson.JsonObject instead of String and call .toString() on that object to get the JSON string itself.
I`m using this site to create my classes (POJO) from JSON.
http://www.jsonschema2pojo.org/
just be sure to set to JSON insted of JSON Schema and check GSON, because retrofit is using GSON as well for parsing.
your retrofit code looks fine.
Use JacksonConverterFactory instead of GsonConverterFactory while setting up Retrofit. Now you can directly work with JsonObject responses.
compile 'com.squareup.retrofit2:converter-jackson:2.1.0'

Retrofit: Sending POST request to server in android

I am using Retrofit to call APIs. I am sending a post request to API but in the callback I am getting empty JSON like this {}.
Below is the code for RetrofitService
#POST("/com/searchusers.php")
void getUser(#Body JSONObject searchstring, Callback<JSONObject> callBack);
where searchstring JSON is like this {"search":"nitesh"}. In response I am supposed to get the detail of user "nitesh".
Below is the code for sending POST request
RetrofitService mRetrofitService = app.getRetrofitService();
mRetrofitService.getUser(user, new Callback<JSONObject>() {
#Override
public void success(JSONObject result, Response arg1) {
System.out.println("success, result: " + result);
}
#Override
public void failure(RetrofitError error) {
System.out.println("failure, error: " + error);
}
});
I am getting this output
success, result: {}
Expected output is
success, result: {"name":"nitesh",....rest of the details}
Edit:
I tried using Response instead of JSONObject like this CallBack<Response> and then I converted the raw response into String and I got the expected result. But the problem is its in String, I want the response in JSONObject.
How can I get the exact result using CallBack<JSONObject> ...?
After waiting for the best response I thought of answering my own question. This is how I resolved my problem.
I changed the converter of RestAdapter of RetrofitService and created my own Converter. Below is my StringConverter
static class StringConverter implements Converter {
#Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
String text = null;
try {
text = fromStream(typedInput.in());
} catch (IOException ignored) {/*NOP*/ }
return text;
}
#Override
public TypedOutput toBody(Object o) {
return null;
}
public static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}
Then I set this converter to the RestAdapter in the Application class.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.setConverter(new StringConverter())
.build();
mRetrofitService = restAdapter.create(RetrofitService.class);
Now whenever I use Retrofit, I get the response in String. Then I converted that String JSONObject.
RetrofitService mRetrofitService = app.getRetrofitService();
mRetrofitService.getUser(user, new Callback<String>() {
#Override
public void success(String result, Response arg1) {
System.out.println("success, result: " + result);
JSONObject jsonObject = new JSONObject(result);
}
#Override
public void failure(RetrofitError error) {
System.out.println("failure, error: " + error);
}
});
Hence, I got the result in JSON form. Then I parsed this JSON as required.
it may help you
JSONObject responseJsonObj = new JSONObject(responseString);

Categories

Resources