I am using JAX-RS for RESTful web services. In doing so I am serializing an object to JSON. My problem is the JSON I get back contains a name attribute that does not exist on my original object. I would like to get rid of it. Example:
public class TestClass {
private string var1;
private int var2;
"getters and setters"
}
The JSON I get returned, once I instantiate, is:
{
"var1": "Hello World".
"var2": 7
"name": "TestClass"
}
How do I get rid of that name attribute?
Related
i have a immutable enum class that i can't change but need to pass value into postman in the same format.
here below is the class.
public class Request {
private int num;
private Type type;
public Request(Type type, int num) {
this.type = type;
this.num = num;
}
public int getNum() {
return num;
}
public Type getType() {
return type;
}
public enum Type {
MEN, WOMEN , FAMILY, CHILD
}
}
i am looking for exact Json format which is pass through Postman. everytime i am getting 400 error while hitting the endpoint.
write a simple program where you can instantiate your Request class and serialize it to JSON String. That would be your JSON that you pass as param. But ultimately the API provider is responsible to tell you what input format is expected.
Here is how you can serialize your class to Json String: you can use JSON Jackson library and use method writeValueAsString Of class ObjectMapper. So, just instantiate your Request class and pass the instance to this method and you will get your Json String. Also I wrote my own JsonUtils utility that my be even simpler but will do the same. use static method JsonUtils.writeObjectToJsonString to serialize your class instance to JSON String. Class JsonUtils comes as part of Open source MgntUtils library. You can get this library as Maven artifact at Maven central or on Github.
Newbie developer here. I am trying to make a call to a public API. The API receives the name of a drink as a string and returns information and recipe for that name. The response from the API looks like this:
{
"drinks":[
{
"id": ...
"name": ...
"recipe": ...
"category": ...
"alcoholic": ...
... many other fields ...
},
{
...
}
...
]
}
I am only interested in name, recipe and category. I have a domain class for this purpose that looks like this
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class Drink {
#JsonProperty("name")
private String name;
#JsonProperty("category")
private String category;
#JsonProperty("recipe")
private String recipe;
}
I also implemented a client to call the endpoint using restTemplate. Here is the call that client makes:
ResponseEntity<List<Drink>> response = restTemplate.exchange(
url,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Drink>>() {
});
My goal is to call the API, get the response and only the fields that I want and store it in a list of Drink. However when I try to run the app locally and make a call I am getting this error:
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<Drink>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<Drink>` from Object value (token `JsonToken.START_OBJECT`)
When I use ResponseEntity<String> instead, it works but returns the whole json as a string, which does not seem like a good approach. How can I get this approach to work?
The problem is mismatch between json structure and object structure. The object you deserialize into must represent correctly the json. It's an object with a field drinks, which is an array of objects(drinks in your case). Correct java class would be:
public class Wrapper {
private List<Drink> drinks;
//getters and setters
#Override
public String toString() {
return "Wrapper{" +
"drinks=" + drinks +
'}';
}
}
Other option would be to write custom deserializer, which can extract drinks from the tree before deserializing directly into a list.]
Edit: Added toString() override for debugging purposes.
I'm using Spring FeignClient to access a RESTful endpoint, the endpoint returns an xml,
I want to get the response as a JSON, which in turn will map to a POJO.
1) When I access the endpoint on the browser, I get response as below,
<ns3:Products xmlns:ns2="http://schemas.com/rest/core/v1" xmlns:ns3="http://schemas/prod/v1">
<ProductDetails>
<ProdId>1234</ProdId>
<ProdName>Some Text</ProdName>
</ProductDetails>
</ns3:Products>
2) #FeignClient(value = "productApi", url = "http://prodservice/resources/prod/v1")
public interface ProductApi {
#GetMapping(value="/products/{productId}", produces = "application/json")
ProductDetails getProductDetails(#PathVariable("productId") String productId)
// where, /products/{productId} refers the RESTful endpoint
// by mentioning, produces = "application/json", I believe the response xml would be converted to JSON Java POJO.
3) POJO
public class ProductDetails {
private String ProdId;
private String ProdName;
//...setters & getters
}
4) Service Layer
ProductDetails details = productApi.getProductDetails(productId);
In the 'details' object, both ProdId & ProdName are coming as null.
Am I missing anything here? Firstly, Is it possible to get response as JSON instead of XML?
If that RESTful service is programmed to return only xml-response, then you cannot ask it to give you json-based response.
But in your case the problem is with class where you want to map the result.
This xml response actually wraps ProductDetails tag into ns3:Products.
So you need to create another class which will hold a reference to ProductDetails object:
public class Product { //class name can be anything
private ProductDetails ProductDetails;
//getters, setters
}
Then change the type of getProductDetails method to Product.
If you still get nulls in your response, then it's probably because of ObjectMapper configuration. But you can always add #JsonProperty annotation for your fields (in
this case it would be #JsonProperty("ProductDetails") for ProductDetails field in Product, and #JsonProperty("ProdId") and #JsonProperty("ProdName") for fields in ProductDetails).
I'm passing a JSON object from a PUT request to my server. The request itself works, however the fields in the JSON which have an underscore (snake_case) seem to bi ignored. The request outputs the received data to see what comes out, and the value with the underscore converts to camelCase, and doesn't get parsed. Here's the class:
Public User{
private int id;
private String name;
private int some_value;
}
The JSON object I pass to the PUT request:
{ "id":1, "name":John, "some_value":5 }
The PUT method only returns what MOXy caught in this case
#PUT
#Path("user")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public User addUser(User user){
return user;
}
And the output is:
{ "id":1, "name":John, "someValue":0 }
Notice how "some_value" changed to "someValue" and didn't get the actual value updated. Any idea on why this is happening?
MOXy follows Java Bean conventions by default, which suggest camel case. If you don't want to (or can't) use camel case, you can add an annotation to the field:
#XmlElement(name = "some_value")
private int some_value;
If you don't want to annotate all your fields, use an XMLNameTransformer.
A Rest service is mapped on one url with some #RequestBody where i am mapping json to pojo. Pojo contains nested classes following is sample code.
#RequestMapping(value = "/saveExampleObject.html", method = RequestMethod.POST)
public #ResponseBody List<String> saveExampleObjectDefintion(#RequestBody ExampleObject exampleObject) throws DataAccessException,DataNotPersistException {
List<String> msg = saveService.save(exampleObject);
return msg;
}
and the object is like
class ExampleObject{
String name;
SubClass subClass;
.....
}
and json is
{
"name":"name",
"subClass":{
.....
}
I have configured spring mvc annotation and conversion is also happening.
But some fields are null. I cross checked names of null field they are same as in json and pojo.
P.S. Only first fields are getting values in subclass.Thanks.
in your json you have subClass but in your class you have subclass... is case sensitive
Here the setters were not defined properly and hence there was an error. Spring MVC uses the setters to properly convert POJO to JSON and vice versa.