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
Related
Im getting the "Value of type java.lang.String cannot be converted to JSONObject" error when trying to pass the response string to the JSON object. I've tried something similar in the past, and it worked, so I have no idea why it's happening.
Here's the code
public void searchMovie(){
OkHttpClient client = new OkHttpClient();
url = Constants.moviebaseurl + mEdit.getText();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String myResponse = response.body().toString();
SearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
JSONArray results = json.getJSONArray("results");
mText.setText(results.getJSONObject(0).getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
Am I doing something wrong, or am I just missing something? Thank you for your help!
It worked changing
final String myResponse = response.body().toString();
for
final String myResponse = response.body().string();
From referencing this question I was able to find this answer
Using google-gson you can do it like this:
JsonObject obj = new JsonParser().parse(myResponse).getAsJsonObject();
This question itself might even lead to some insight of the issue if my code doesn't work for you.
I am trying to integrate greendao with the retrofit. This link will give an idea ( https://i.stack.imgur.com/7qmbu.jpg) of how the data is sent to the server. It is a post request and I am really confused about how to call this request via retrofit.
It will be really helpful if someone can help me with it.
In API response I am getting an request object, response object, message and status code.
response object I have fields about the user and in request object I have field about the information that is being send.
another picture here
https://i.stack.imgur.com/a5DBz.jpg
You can create response like this using this method
private String create(String email, String password) {
try {
JSONObject cell1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
cell1.put("email", email);
cell1.put("password", password);
jsonObject.put("data", cell1);
return jsonObject.toString();
} catch (Exception e) {
return e.getMessage();
}
}
Call you POST as this
#FormUrlEncoded
#POST("your_path_here")
Call<String> uploadData(#Body String obj);
in your Activity
String json = create("your_email", "your_password");
apiInterface.uploadData(json).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
http://www.superbinstruments.com/directory/index.php?r=webservice/profile/id/4096
Here i want to pass ID in the URL (like above) and JsonObject (can be null) in the Body.
Here the concept is like when i pass null to the json object it will retrieve the profile data or if i pass the json object with profile information then it will update the profile data.
I have tried below methods but i can retrieve the data but i can not update the data.
To update the data we we can pass same JSON response as Body.
#POST("index.php")
Call<UserProfile> profileUser(#Query("r") String value, #Body String user);
#POST("index.php?")
Call<UserProfile> saveUser(#Query("r") String value, #Body JSONObject user);
I am passing like:
value= webservice/profile/id/4096
if I pass as Json String as profile updated info then i am getting
"Invalid request password not needed."
OR
if I will pass as JsonObject as profile updated info
then i am getting
java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available
The link you have posted not required any body to post. Remove Body from your code. To use #Field you have to annotate method as #FormUrlEncoded
Your method should be like this.
#FormUrlEncoded
#POST("index.php?r=webservice/profile/id/")
Call<UserProfile> saveUser(#Field("value") String value);
Hope it helps:)
Please try this way
#POST("index.php")
Call<User> getInstruments(#Query("r") String webservice, #Body User user);
And you should have to pass JSON using your model class as Bhuvanesh suggested
JSONObject jObj = null;
try {
jObj = new JSONObject();
jObj.put("firstname", "Kunjan Shah");
} catch (JSONException ex) {
ex.printStackTrace();
}
User user = new User();
user.setData(jObj);
And here is your model class
public class User {
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public JSONObject getData() {
return data;
}
public void setData(JSONObject data) {
this.data = data;
}
String success;
String message;
JSONObject data;
}
And call your service by passing this two parameter
Call update_user_profile =
yourapiinterfaceobject.getInstruments("webservice/profile/id/4096", user);
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
}
I have to send the JSON as a Post request through Retrofit. To this I have created a Json Object :
private JSONObject yourJSON(){
JSONObject jsonRoot = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject2 = new JSONObject();
try{
jsonArray.put(jsonObject2);
jsonObject2.put("duration", "12");
jsonObject1.put("region", "NYC");
jsonObject1.put("or", jsonArray);
jsonRoot.put("q", jsonObject1);
jsonRoot.put("sort", "recent");
}catch (JSONException e){
e.printStackTrace();
}
return jsonRoot;
}
Then I am using this JSON to send the data by following code
RestApiAdapter restAdapter = new RestApiAdapter();
RoomListingAPI apiservice = restAdapter.providesRestAdapter().create(RoomListingAPI.class);
JSONObject response = apiservice.getRoomListing("qwerty","application/json", yourJSON());
API method
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
My goal is to send the JSON and received the JSON but it's not working. What I am doing wrong here. I am also sending the correct JSON. What I am doing wrong here?
You should call your network operation on a background task instead. Otherwise, NetworkOnMainThreadException will be thrown.
Now retrofit has two modes. Synchronous or Asynchronous.
You're using a synchronous mode, presumably called in your main thread.
What you can do now is to change to asynchronous mode (using retrofit callback).
That is, change from:
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
To:
public interface RoomListingAPI {
#POST("/api/listings/search")
void getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json, Callback<JsonObject> responseCallback);
}
To get the JsonObject return response:
apiservice.getRoomListing("qwerty","application/json", yourJSON(),
new Callback<JsonObject>() {
#Override
public void success(JsonObject jsonObject, Response response) {
// jsonObject is what you're looking for
}
#Override
public void failure(RetrofitError error) {
// do something with the error
}
});
Also, it's better to use gson library. Thus use JsonObject instead of JSONObject. Different letter-case, different library, better performance.