Skip to main content
Calling a rest service with spring rest + json jackson Presenting to you step by step a tutorial about the use of some apis that leverage the logic for calling to a rest service and also the json parting and marshalling process
First Step Importing required libs:

You will need to import spring for droid there are the files:
spring-android-auth-1.0.0.M4.jar
spring-android-core-1.0.0.M4.jar
spring-android-rest-template-1.0.0.M4.jar


You will need to import jackson lib there is the file:
jackson-all-1.9.4.jar

Second Step : Declaring variables
You will need these three variables to do the trick. I will recomend to declare them as fields and instantiate them later on class constructor.

RestTemplate restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory();


Third step: Calling rest service:

Just call this method of rest template and the api will call the service and will encapsulate all the stream stuff and present you the response as a string file in this example.

String url = "yourjsonrestserviceurl");
String result = restTemplate.getForObject(url, String.class);


Fourth Step: Creating json parser and marshalling the json result into an object

JsonParser jp = jsonFactory.createJsonParser(result);
MappingIterator list = objectMapper.readValues(jp, YourBean[].class);


Finally Some recomendations:
You should get some errors depending of the format of your json. Here are some workarounds:

to map a field with different names:
Add anotation @JsonProperty("yourJSONfield") to the POJO field you want to map.
To ignore a POJO field on marshalling process: @JsonIgnore

Comments

Popular posts from this blog

Quarkus goes Reactive☢

In this tutorial I will explain how to create a quarkus based java application that will use reactive datasource to connect to a postgres database and be able to perform crud operations via rest endpoint. To make it more real this application will also be published into kubernetes cluster and will use configmap to store datasource configuration. To lern more about benefits of reactive data sources vs. jdbc regular data sources you can go to following link https://cutt.ly/1l260tK.  Step 1: Configure Project 

Register new WCS store view by using database

To register a new view by using SQL queries: insert into acaction (acaction_id, action) values ((select counter from keys where tablename='acaction'), 'NewView');  insert into acactactgp (ACACTGRP_ID,ACACTION_ID) values  ((SELECT ACACTGRP_ID FROM ACACTGRP WHERE GROUPNAME = 'AllSiteUsersViews'  and member_id in (select orgentity_id from orgentity where orgentityname='Root Organization')  ),  (select acaction_id from acaction where action='NewView'));  UPDATE KEYS SET COUNTER = COUNTER+1 WHERE TABLENAME = 'acaction'; commit