This is my POST request to an API
ResponseEntity<String> result = rt.exchange(url, HttpMethod.POST, httpEntity, String.class);
The response i am getting is below
{
"headers": {
"Cache-Control": [
"no-store"
],
"Content-Type": [
"application/json;charset=UTF-8"
],
"Date": [
"Thu, 20 Jun 2019 12:50:08 GMT"
],
"Pragma": [
"no-cache"
],
"Server": [
"val"
],
"X-Content-Type-Options": [
"nosniff"
],
"X-Frame-Options": [
"DENY"
],
"X-Xss-Protection": [
"1; mode=block"
],
"Content-Length": [
"331"
]
},
"body": {
"access_token": "token_value,
"scope": "KYC",
"token_type": "bearer",
"expires_in": 49900,
"jti": "jti_val"
},
"statusCode": "OK",
"statusCodeValue": 200
}
I need to get extract
access_token,scope,token_type,statusCodeValue
So what should be structure of my POJO class to map the response ?Or how can i get the values from JSON for those fields ?
ResponseEntity<PojoClass> result = rt.exchange(url, HttpMethod.POST, httpEntity, PojoClass.class);
Body can get through the snippet posted above and status code can be retrieved using "response.getStatus()"
try this:updated
ResponseEntity<Response> response = rt.exchange(url, HttpMethod.POST, httpEntity, Response.class);
Class definition:
Body Class:
public class Body implements Serializable{
private String access_token;
private String scope;
private String token_type;
private long expires_in;
private String jti;
//standard getters and setters
}
Response class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable{
private String statusCode;
private int statusCodeValue;
private Body body;
//standard getters and setters
}
Now:
you should access your desired values using their respective getters method.
like:
String token=response.getBody.getAccessToken();
String statusCode= respnse.getStatusCode();
Related
I use Spring-boot and RestTemplate.
I'm having trouble translating from json to Dto.
Client
Items items = restTemplate.getForObject("https://xxxxx/xxxxx, Items.class);
Items
#Getter
#Setter
#AllArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = false)
public class Items {
private List<Item> Items;
public Items() {
Items = new ArrayList<>();
}
#Override
public String toString() {
return String.valueOf(Items.size());
}
}
Item
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class Item {
private String title;
#Override
public String toString() {
return "Item{" + "title=" + title + '}';
}
}
Json is here(formatted).
{
"Items": [
{
"Item": {
"limitedFlag": 0,
"authorKana": "XXX",
"author": "XXX",
"subTitle": "XXX",
"seriesNameKana": "XXXX",
"title": "XXXX",
"subTitleKana": "XXXX"
}
},
{
"Item": {
"limitedFlag": 0,
"authorKana": "XXX",
"author": "XXX",
"subTitle": "XXX",
"seriesNameKana": "XXXX",
"title": "XXXX",
"subTitleKana": "XXXX"
}
}
],
"last": 30
}
I receive this error message:
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `[Ldev.itboot.mb.rest.Item;` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[Ldev.itboot.mb.rest.Item;` from Object value (token `JsonToken.START_OBJECT`)
I looked here and on google but still cannot figure out.
Any response would be helpful.
Regards.
The end of your JSON seem incorrect, there should be a comma after the array, before "last".
]
"last": 30
}
Hi I have to send a POST request with resttemplate.exchange with these parameters
{
"tipoPortafoglio": "string",
"allegatiPratica": [
{
"fileName": "string",
"body": "string",
"mimeType": "string"
}
]
}
I have a mapped class of this called
Public class CreateRichiesta {
String tipoPortafoglio
Allegato allegatiPratica //<===== Custom type defined as JSON
//Getter and setters
I cannot pass the entity to RestTemplate.Exchange with HashMap because of customtype infact
Map<String,String> input = new HashMap<>();
input.put("tipoPortafoglio", request.getTipoPortafoglio());
input.put("allegatiPratica", request.getAllegatiPratica()));
getAllegatiPratica is not string type but Allegato type
How can i do??Thx to all
HttpEntity<CreateRichiesta> request = new HttpEntity<>(new CreateRichiesta());
ResponseEntity<CreateRichiestaResponse> responseEntityObj = restTemplate
.exchange(resourceUrl, HttpMethod.POST, request, CreateRichiestaResponse.class);
I got a null object attributes after deserialization of a json response.
Developing under android, I'm using retrofit2 , moshi as converter (https://github.com/kamikat/moshi-jsonapi ) .
When debugging ,I saw a json response fully retrieved (not null attributes),but deserialization fails. Should I use GSON instead?
Here's my retrofit builder I use to make my json call: (no issue)
public static JsonServerInterface getSimpleClient(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_AUTH_URL)a
.addConverterFactory(MoshiConverterFactory.create())
.build();
JsonServerInterface webServer=retrofit.create(JsonServerInterface.class);
return webServer;
}
My api json call,response contain UserModel with null attributes(deserialization fails without any error)
signInCall.enqueue(new Callback<UserModel>(){
#Override
public void onResponse
(Call<UserModel> call, Response<UserModel> response)
{
response.message();
}
}
My UserModel (as required by moshi ,but I think it lacks something):
#JsonApi(type = "users")
public class UserModel extends Resource {
#Json(name = "auth-token")
private String authToken;
#Json(name = "firstname")
private String firstname;
#Json(name = "lastname")
private String lastname;
#Json(name = "email")
private String email;
#Json(name = "created-at")
private String createdAt;
#Json(name = "updated-at")
private String updatedAt;
private HasMany<ActivityModel> activities;
My json response I saw when debugging http response, I retrieve without any trouve,but moshi sucks to deserialize it,and no errors are raised:
{
"data": {
"id": "21",
"type": "users",
"attributes": {
"auth-token": "t8S3BTqyPwN3T4QDMY1FwEMF",
"firstname": "aymen",
"lastname": "myself",
"email": "aymen.myself#gmail.com",
"created-at": "2017-11-13T22:52:39.477Z",
"updated-at": "2017-11-13T23:21:09.706Z"
},
"relationships": {
"activities": {
"data": [
{
"id": "81",
"type": "activities"
}
]
}
}
},
"included": [
{
"id": "81",
"type": "activities",
"attributes": {
"title": "activity 10",
"description": "how to draw a circle",
"start-at": "2017-11-13T23:06:13.474Z",
"duration": 10,
"created-at": "2017-11-13T23:06:32.630Z",
"updated-at": "2017-11-13T23:06:32.630Z"
},
"relationships": {
"user": {
"data": {
"id": "21",
"type": "users"
}
}
}
}
]
}
I find the solution after lot of hours:
I should use "Document" instead of UserModel
interface:
#POST("sign-in.json")
Call<Document> signIn(#Body Credentials credentials);
when calling:
signInCall.enqueue(new Callback<Document>(){
#Override
public void onResponse(Call<Document> call, Response<Document> response) {
hope it helps
I'm using RestTemplate to retrieve list of issues from Jira. As response I get String with lots of fields, some of them are arrays. Request looks like:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
Response string looks like:
{
"expand": "schema,names",
"total": 12,
"issues": [
{
"id": "32",
"key": "TEST-1",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-02"
}
]
},
{
"id": "32",
"key": "TEST-2",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-01"
}
]
}
]
}
Is it possible to convert this String into Map, where Object could be String or List of Map or something like this, without defining appropriate objects. As result, I'd like to have possibility to access description by: response.getIssues().get(0).getFields().getFixVersion().get(0).getDescription()
In such occasion, defining chain of specific objects looks too cumbersome.
You can create your own POJO classes which corresponds to the structure of the response JSON.
Based on the json that you have shared, you can have a class structure like this :
public class Response {
private String expand;
private String total;
private List<Issues> issues;
}
public class Issues {
private String id;
private String key;
private Map<String, List<FixVersions> fields;
}
public class FixVersions {
private String description;
private String releaseData;
}
Your GET call will change to the following :
ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET, entity, Response.class);
P.S. - All the fields in the POJO class must have their getters and
setters as well.
I am consuming some XML exposed from a REST application and want to expose this as JSON in my own REST service.
Right now I have the following POJO:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"salesMarket"
})
#XmlRootElement(name = "salesMarkets")
public class SalesMarkets {
protected List<SalesMarket> salesMarket;
public List<SalesMarket> getSalesMarket() {
if (salesMarket == null) {
salesMarket = new ArrayList<SalesMarket>();
}
return this.salesMarket;
}
}
Which produces the following JSON:
"salesMarkets": {
"salesMarket": [
{
"brands": {
"brand": [
"DAN"
]
},
"code": "999"
},
{
"brands": {
"brand": [
"DAN"
]
},
"code": "208"
}
]
}
My question is (using Jackson annnotations), is there a way to avoid the class name being serialized as JSON??, so I instead would have:
"salesMarket": [{
"brands": {
"brand": [
"DAN"
]
},
"code": "999"
}, {
"brands": {
"brand": [
"DAN"
]
},
"code": "208"
}]
I'm thinking some Jackson annotaion on the class SalesMarkets... But havn't been succesfull yet :-(
UPDATE:
Just realised that the SalesMarket class was referenced from another class - which is why the "salesMarkets" appears in the JSON. Is there a way to annotate the SalesMarkets field, so that it is ignored but not the fields contained there in?:
#XmlRootElement(name = "product")
public class Product {
#XmlElement(required = true)
protected String propertyID;
#XmlElement(required = true)
protected String season;
**protected SalesMarkets salesMarkets;**
protected Information information;
protected Features features;
protected Location location;
protected Address address;
protected Buildings buildings;
protected Pictures pictures;
protected Media media;
protected Prices prices;
protected Offers offers;
protected Availabilities availabilities;
protected Services services;
protected Concepts concepts;
...
You need to either remove
#XmlRootElement(name = "salesMarkets")
Or disable the feature on ObjectMapper:
objectMapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)
To further unwrap salesMarkets field in Product instances you can do the following:
public class Product {
protected SalesMarkets salesMarkets;
public List<SalesMarket> getSalesMarkets(){
if(salesMarkets != null){
return salesMarkets.getSalesMarket();
} else {
return null;
}
}
}