iam trying to get json resopse like this but it come with improper json format how can get the string in proper format
Call<HashMap<Object,Object>> call = RestClient.getClient().aladata(AppUtil.getAuthKey(DashboardActivity.this),String.valueOf(mSelectedCategory.getId()), String.valueOf(mLat), String.valueOf(mLng), String.valueOf(50), String.valueOf(offset * 50));
call.enqueue(new Callback<HashMap<Object,Object>>() {
#Override
public void onResponse(Call<HashMap<Object,Object>> call, Response<HashMap<Object,Object>> response) {
String hashMapString=response.body().toString();
try {
JSONObject jsonObject=new JSONObject(hashMapString);
String jsonstr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<Object,Object> hashMap2=response.body();
}
#Override
public void onFailure(Call<HashMap<Object,Object>> call, Throwable t) {
}
});
}
When you work with Retrofit should to use JsonObject instead of JSONObject.
Hope it helps!
Related
I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.
The JSON in ALE2 file
{
"a1":[...],
"a2":[...],
"a3":[...]
}
Code
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
#Override
public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {
}
#Override
public void onFailure(Call < JSONObject > call, Throwable t) {
}
});
RetrofitInterface
public interface RetrofitInterface {
#GET("ALE2")
Call<JSONObject> getData();
}
I don't want to store them in any model I just want to get the JSON as a string
Your interface should look like this :
public interface RetrofitInterface {
#GET("ALE2")
Call<ResponseBody> getData();
}
To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is how you can set string in JSON object.
every time i run this function onfaliure calls
json array
{"ORDER":[{"ORDER_DATE":"2020-09-08 01:28:11 PM","CUSTOMER_ID":"umersaleem_03334033313","PRODUCT_ID":"","QUANTITY":1,"DEAL_ID":"1","ORDER_TOTAL":"600.0"}
interface
#POST("/restaro/index.php/Home/insert_order_info")
Call<CheckloginModel> insertOrder(#Body JSONObject j);
function
retrofitApiInterface.insertOrder(orders)
.enqueue(new Callback<CheckloginModel>() {
#Override
public void onResponse(Call<CheckloginModel> call, Response<CheckloginModel> response) {
if (response.isSuccessful()) {
}
#Override
public void onFailure(Call<CheckloginModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Poor internet connection or device is Off ", Toast.LENGTH_SHORT).show();
}
});
}
api response
this the response when the data is inserted through postman
{
"status": 1,
"message": "new order added "
}
when i send it on postman the data is inserting need help thanks in advance
#Headers("Content-Type: application/json")
#POST("/restaro/index.php/Home/insert_order_info")
Call< CheckloginModel> insertOrder(#Body RequestBody body);
request body send with your json and send this request body to api.
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("value", "value");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonObject.toString());
I will only this line and pass requestbody Retrofit call and works for me
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString());
Call<CheckOutResponse> call = RetrofitClient.getInstance().getApi().postOrder(requestBody);
call.enqueue(new Callback<CheckOutResponse>() {
#Override
public void onResponse(Call<CheckOutResponse> call, Response<CheckOutResponse> response) {
CheckOutResponse checkOutResponse = response.body();
#Override
public void onFailure(Call<CheckOutResponse> call, Throwable t) {
}
});
Webservice class
#POST("yourAPiCall")
Call<CheckOutResponse> postOrder(#Body RequestBody requestBody);
In my retrofit JSON response there is a single value without any key and type.In my JSON i have passed three-element as per need and now i get a response as shown below. so how can I fetch that response?
My JSON of Response looks like -
successful
This is my JSON code-
private void ASSIGN_DATA() {
ApiInterface apiInterface=ApiClient.getClient().create(ApiInterface.class);
Call<ArrayList<price_get_set>> call=apiInterface.assignItemToJson(select_date.getText().toString(),
id,item_list);
call.enqueue(new Callback<ArrayList<price_get_set>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<ArrayList<price_get_set>> call, Response<ArrayList<price_get_set>> response) {
progress.dismiss();
Log.d("URL::",response.toString());
Log.d("new URL::",response.body().toString());
try {
if (response.isSuccessful()) {
Toast.makeText(Items_List.this, "Successs", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Items_List.this, Item_Accept_Reject_List.class);
startActivity(intent);
}
else
Toast.makeText(Items_List.this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
catch (Exception ex){
Log.e("ERROR::",ex.getMessage());
}
}
#Override
public void onFailure(Call<ArrayList<price_get_set>> call, Throwable t) {
progress.dismiss();
Log.i("FAILURE ERROR::",t.getMessage());
}
});
}
You can use response.body().string().
It will convert your response in String.
Example On Your onResponse method of API you have to use this code.
#Override
public void onResponse(Response<ResponseBody> response) {
try {
String responseString = response.body().toString();//This a response as string
Log.d("Response : " + responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
this below code is calling webservice which i want to implementing that with Retrofit on Android, but i get this error:
No Retrofit annotation found
calling Web Service with CURL:
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
-H "X-User-Id: aobEdbYhXfu5hkeqG" \
http://localhost:3000/api/v1/channels.list
i wrote this interface like with above code:
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
ChannelsList channelsList);
}
and i'm calling this rest Web Service by this code:
ChannelsList channelsList = new ChannelsList();
Call<List<ChannelsList>> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD",
channelsList);
call.enqueue(new Callback<List<ChannelsList>>() {
#Override
public void onResponse(Call<List<ChannelsList>> call, final Response<List<ChannelsList>> response) {
Log.e("contentLength ", response.code() + "");
}
#Override
public void onFailure(Call<List<ChannelsList>> call, Throwable t) {
t.printStackTrace();
}
});
whats problem of my code that i can't call and i get error?
You forgot #Body annotation. And since you have to send a body, you must create a POST to your API. If is not a POST, you must find how to send ChannelsList in order to be a GET request because is depending your server implementation.
#POST("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
#Body ChannelsList channelsList);
problem solved by this below code:
interface:
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<ResponseBody> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId);
}
call request and get response:
ChannelsList channelsList = new ChannelsList();
Call<ResponseBody> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String jsonString = response.body().string();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonarray = jsonObject.getJSONArray("channels");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Err: ", t.getMessage());
}
});
Currently, I am using Retrofit to get data from api. But the format of data is a bit different from other format such as :
["tayl",["taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"]]
So, I want to ask for the best solution to parse values to get a list as below if I want to use retrofit:
"taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"
The content of the file above is the data which GoogleAutoComplete Api returned for me with the link below :
http://suggestqueries.google.com/complete/search?client=firefox&q=tayl
I implemented the code as below but it is not good:
#Headers({
"Accept: application/json",
"Content-Type: application/json; charset=UTF-8"
})
#GET("complete/search?")
Call<ResponseBody> getAutoComplete(#Query(#Query("q")String query);
The below is response code which I am using:
autoCompleteCall = googleApi.getAutoComplete(client, keyword);
autoCompleteCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response != null &&
response.body() != null) {
System.out.println(" String response======= " + response.body().toString());
return;
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
But the responsebody returned for me is null.
Please help me in this case.
Thanks.
Define the API endpoint in an interface as follows:
#GET("complete/search")
Call<ResponseBody> getAutoComplete(
#Query("client") String client,
#Query("q") String query);
Make the network request as follows:
Call<ResponseBody> call = service.getAutoComplete("firefox", "tayl");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
try {
// autocompleteOptions => ["tayl",["taylor swift","taylor lautner",...
String autocompleteOptions = body.string();
JSONArray jsonArray = new JSONArray(autocompleteOptions).getJSONArray(1);
// list => "taylor swift","taylor lautner",...
ArrayList<String> list = GetAutocompleteOptions(jsonArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
private ArrayList<String> GetAutocompleteOptions(JSONArray jsonArray) throws JSONException {
ArrayList<String> list = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}
}
return list;
}