How do I pass Dynamic JSON file name using Retrofit
MainActivity.java:
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint("http://www.domain.com/").build();
api flowerapi = restadapter.create(api.class);
api.java:
public interface api {
#GET("/JSONS/flowers.json")
void getData(Callback<List<Flower>> response);
}
As you can see in my above code, I am using only single/one and only flowers.json
What If I would like to call dynamic json files based on some conditions, like in some cases I have to call flowers.json, in some cases roses.json and in some cases something.json
with the #Path annotation
#GET("/JSONS/{name}")
void getData(#Path("name") String name, Callback<List<Flower>> response);
Related
I'm currently using rest assured and Json-unit to assert a local json file against the requested rest assured response.
I currently have a before class method with my base uri.
I don't know how to make this assertion. I'm struggling with the json-unit documentation. Do I need to input a file first?
#Test
public void ApiaryTest1() throws Exception {
when()
.get("/test")
.then()
.statusCode(200);
// compares two JSON documents
assertJsonEquals("expected/test.json", "http://apiary/test");
}
You need to:
Read in the resource with the JsonUnit API
Extract the response from rest assured to a variable
Assert you are already doing
Example:
Response response = when().get("<url>");
response
.then()
.statusCode(200);
// compares two JSON documents
assertJsonEquals(resource("resource-inside-resources-folder.json"), response.asString());
For Restassured Kotlin DSL:
When {
get("http://nowjidev1vm01.ath.bskyb.com/calskyplussearch/health")
} Then {
statusCode(200)
} Extract {
assertJsonEquals(expectedBody, response().asString())
}
It is easier than you think. Rest Assures is passing the entire body as string in case of a "body matcher" is specified. Therefore you can just use the jsonEquals matcher of json unit directly:
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
public class RestAssuredWithJsonUnit {
#Test
public void test() throws Exception {
given().when().get("/api/service/v1").
then().
statusCode(200).
body(jsonEquals(resource("resource-on-classpath.json")));
}
public static String resource(String resourceName) throws IOException {
Objects.requireNonNull(resourceName, "'null' passed instead of resource name");
return IOUtils.resourceToString(resourceName, UTF_8);
}
Please note the implementation of the "resource" method. The one provided in ResourceUtils is using the system classloader, which did not found my resoulces unfortunately. IOUtils from commons-io does the job well!
Hello I am working on an Android App which uses retrofit API getting response from server. Retrofit Automatically parse the json response and creates objects of POJO class. I am storing that json into sqlite and if internet is not connected call the json from sqllite, facing difficulty have to parse json manually.
Is there any way I use retrofit library to parse json and make pojo from json string or file path?My code is here to fetch from url:
#FormUrlEncoded
#POST("getResponse")
Observable<UserResponse> getResponse(#Field("token") String token);
I want something like this if internet is not connected.
#FromStringEncoded
Observable<UserResponse> getResponseOffline(#Field("token") String token);
Thanks.
You don't mentioned proposes. I use below solution for mocking server in app on very early stage of development when real server doesn't work yet.
So you can use interceptors in OkHttp. Like this:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new MockClient(context));
and MockClient looks like this:
public class MockClient implements Interceptor {
Context context;
public MockClient(Context context) {
this.context = context;
}
#Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url();
Log.d("TAG","url="+url);
//here determine what to do base on url.
//e.g.:
switch(url.encodedPath()) {
case "some/path" :
String response = readJsonFieleFromAssestOrAnyOtherStorage();
return new Response.Builder()
.code(200)
.message(response)
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.body(ResponseBody.create(MediaType.parse("application/json"), response.getBytes()))
.addHeader("content-type", "application/json")
.build();
}
}
}
Simply use Google's GSON Library that allows you to convert json to POJO and vice versa. Fetch json from sqlite and parse it using gson.
Gson gson=new Gson();
UserResponse userResponse= gson.fromJson(jsonInStringFromDb,UserResponse.class);
You can also parse JSON from file using Gson.
JSON to Java object, read it from a file.
Gson gson = new Gson();
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
THere's no point in using it from the local filesystem- retrofit is for http requests. If you need to just parse JSON, use GSON or Jackson- those are the two libraries that RetroFit uses to parse json. Both libraries are fairly easy to use.
We're using retrofit android client (http://square.github.io/retrofit/) for network calls to our server and I cant figure out how to access values in the strings.xml file from the interface class that we created for retrofit.
Here's a small sample of our interface code.
//all retrofit imports
public interface APIService {
String API_KEY = "XXXX"; //Get this value from strings.xml
#GET("/api/getNames?api_key=" + API_KEY)
public ArrayList<String> getNames();
}
Right now XXXX is hardcoded but we want it to get taken from strings.xml.
Thank you.
You can pass the API_KEY as a parameter using
#GET("/api/getNames")
public ArrayList<String> getNames(#Query("api_key") String apiKey);
Check URL manipulation section URL Manipulation - Retrofit
I'm trying to pass a string of the format below as the body of a http post request.
param1=PARAM1¶m2=PARAM2¶m3=PARAM3
But retrofit encodes my body so that = becomes \u003d and & becomes \u0026. And I end up with a string which actually looks like this:
param1\u003dPARAM1\u0026param2\u003dPARAM2\u0026param3\u003dPARAM3
How can I prevent that?
My retrofit rest api is defined as follows.
public interface RestAPI {
#POST("/oauth/token")
public void getAccessToken(#Body String requestBody, Callback<Response> response);
}
If you have a serialized class (like a HashMap) in the request body and you want to prevent encoding that (like in vezikon's and my problem), you can create a custom Gson with disabled escaping using:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Pass this converter to your rest adapter:
yourRestAdapter = new RestAdapter.Builder()
.setEndpoint(.....)
.setClient(.....)
.setConverter(new GsonConverter(gson))
.build();
This way the "=" characters in the post body stay intact while submitting.
To answer the question directly, you can use TypedString as the method parameter type. The reason the value is being changed is because Retrofit is handing the String to Gson in order to encode as JSON. Using TypedString or any TypedOutput subclass will prevent this behavior, basically telling Retrofit you will handle creating the direct request body yourself.
However, that format of payload is called form URL encoding. Retrofit has native support for it. Your method declaration should actually look like this:
#FormUrlEncoded
#POST("/oauth/token")
void getAccessToken(
#Field("param1") String param1,
#Field("param2") String param2,
#Field("param3") String param3,
Callback<Response> callback);
Using Kotlin
For Retrofit 2 you can initialize retrofit with a Gson converter factory.
val builder = GsonBuilder().disableHtmlEscaping().create()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(builder))
.client(monoOkHttpClient())
.build()
This builder should remove escaping from your json output.
Gradle file dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
This issue can be fixed with below workaround.
#POST("yourString")
Call<YourResponseModel> yourCallMethod(#Query("yourKey") String yourValue,
#Query("yourKey") String yourValue,
#Query("yourKey") String yourValue);
Note : Don't use "#FormUrlEncoded" for this case.
Reference Here - https://github.com/square/retrofit/issues/1407
I have downloaded the retrofit library and samples from https://github.com/square/retrofit.I want to do image and data caching.
But I am not getting how to use that in android.Can Somebody give me an example.I have checked the code
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("")
.build();
ClientInterface service = restAdapter.create(ClientInterface.class);
Callback callback = new Callback() {
#Override
public void success(Object o, Response response) {
// Read response here
}
#Override
public void failure(RetrofitError retrofitError) {
// Catch error here
} };
service.findBuffet("sudhakar", callback);
But I am not getting anything.
Thanks for the help in advance...
You have to create an interface like below.
public interface MyService {
#GET("/getUser/{user}")
User getUserDetails(#Path("user") String userId);
}
Create your rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://mybaseurl.com")
.build();
MyService service = restAdapter.create(MyService.class);
Get user details like this:
User user = service.getUserDetails("123456");
To get a successful result you have to define your pojos correctly.
You can use this link to create your pojos : http://www.jsonschema2pojo.org/
Retrofit is best to use. follow are the steps to use retrofit.
Please get details process here
Step 1- add dependency
Step 2 - init retrofit and add wrapper functions to call interface
Step 3 - Create POJO model using any online jsoneditor like jsoneditor.org
Step 4 - Create interface (URL from where you want to fetch date)
Step 5 - Call wrapper function from activity.