Ignore a java bean field while converting to jSON - java

Ignore a java bean field while converting to jSON
I am having a java bean and sending JSON as response , In that java bean I want to have
some transient fields , that should not come into JSON .
#XmlRootElement(name = "sample")
class Sample{
private String field1;
#XmlTransient
private String transientField;
//Getter and setters
public String toJSON() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
}
When I am calling toJSON method I am still getting "transientField" in JSON.
And I have a get rest API that returns this Sample JSON as response.
#GET
#Path("/somePath/")
#Produces({"application/json"})
Sample getSample();
In this response also I am getting that transient field .
Am I doing something wrong? Please help me to do this .

Try using #JsonIgnore instead.

method 1: use annotation #JsonIgnoreProperties("fieldname") to your POJO
example : #JsonIgnoreProperties(ignoreUnknown = true, value = {"fieldTobeIgnored"})
method 2:#JsonIgnore for a specific field that is to be ignored deserializing JSON

Related

Retrieving Java Objects from a json post request

I am developing a restful web application using java and jax-rs. In server side, I have to accept Json type requests as given by the client using POST method.
#POST
#Path("/Request")
#Consumes(MediaType.APPLICATION_JSON)
public String process(SMessage message) throws Exception {
message.getHeader();
message.getBody();
}
The json object have two composite fields like in the below format.
{
"header": {
"serviceType": "A"
},
"body": {
"id": "1",
"name": "abc"
}
}
Based on the serviceType specified in the Header field, the parameters in the body will differ. I need to map this body field in to a java POJO class. The POJO class is not the same for all requests. How can I achieve this effectively?
If you are using Jackson as your JSON parser, a simple way is to declare body to be a JsonNode to handle dynamic keys as follows:
class MyResponse {
private MyHeader header;
private JsonNode body;
//general getters and setters
}
And I assumed that you have already a POJO for header such as:
class MyHeader {
private String serviceType;
//general getters and setters
}
Finally, let's verify that it works:
String responseStr = "{\"header\": {\"serviceType\": \"A\"},\"body\": {\"id\": \"1\",\"name\": \"abc\"}}";
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(responseStr, MyResponse.class);
System.out.println(myResponse.getBody().get("name").asText());
Console output:
abc
Another way to solve this issue is by using Map and everything else is the same:
class MyResponse {
private MyHeader header;
private Map<String, Object> body;
//general getters and setters
}

creating nested Json in Java

Im trying to get the Json inside Json response of the rest api.
httpsConn.getInputStream() will be a Json like
"data":[
{"id":"1","name:"aaa","score":"90"},{"id":"2","name":"bbb","score":"85"}
]
Jave code:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
response = (MarkResponse)objectMapper.readValue(httpsConn.getInputStream(), MarkResponse.class);
Pojo class:
public class MarkResponse {
private int count;
private List<MarkData> markData;
//setter and getter.
}
public class MarkData {
private String id;
private String name;
}
The response is like below, as I'm using the List inside my main pojo.
{"headers":{},"body":"MarkResponse [count=2 markData=[MarkData [id=1,
name=aaa], MarkData
[id=2,name=bbb]]],"statusCode":"ACCEPTED","statusCodeValue":202}
What I'm expecting is,
{"headers":{},"body":"MarkResponse [count=2
markData={"id":"1","name:"aaa"},{"id":"2","name":"bbb"}],"statusCode":"ACCEPTED","statusCodeValue":202}
What is the code change i should make to get the expected output.
I think the problem is private fields. When I make fields public, jackson works and I don't need to objectMapper.disable(anything); when fields are private, or protected, or package-private, they are read, but not written to.
That is, assuming that you try to use org.codehaus.jackson.map.ObjectMapper (yes, not the latest version) rather than something else that defines a class named ObjectMapper.
This works after changing the return type.
My earlier response was,
public ResponseEntity<String> fnCall() {
//code here
return new ResponseEntity<String>(MarkResponse.toString(), HttpStatus.ACCEPTED);
}
I changed this to make it work.
public MarkResponse fnCall() {
//code here
return response;
}

How to read a single JSON field for a specific Java type with Jackson?

I'm trying to build a JPA CriteriaQuery from a client-provided JSON filter; that is, to query this Person POJO:
#Entity
public class Person {
#Id
public Long id;
public String name;
public Date dateOfBirth;
}
a client would provide a JSON like this
{
"$or": [
{ "name": { "$beginsWith": "Jo" } },
{ "dateOfBirth": { "$lessThan": "1983-01-01T00:00:00Z" } }
]
}
When parsing this filter, I need to obtain the right Java type from the provided JSON values, e.g. a Date for dateOfBirth. Given that I can easily reach the JsonNode for "1983-01-01T00:00:00Z" and that Jackson's ObjectMapper knows somewhere what type to deserialize for the dateOfBirth field of Person.class, how can I get it? Ideally it would be something in the lines of:
// jsonNode is the JsonNode for "1983-01-01T00:00:00Z"
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerFor(Person.class);
Date date = (Date) reader.asField("dateOfBirth").readValue(jsonNode);
That asField() method would do the magic to return a reader which will read a JSON string as Java Date (or more generally the type that the ObjectMapper would resolve applying [de]serializers annotated for that field).
Note: I'm not asking how to parse dates with Jackson, but how to read a value and get the object Jackson would deserialize normally, but for a nested field.

Spring mvc mapping json to pojo properties are null

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.

Jersey - JSON marshall only specific fields

My REST service returns following JSON
{
"name": "John",
"id" : 10
}
Can I use Jersey to marshall it into following Bean:
public class User{
private String name;
//getter & setter
}
I wanted to do this with following code but it doesn't work
WebResource webResource = client.resource(url);
webResource.accept(MediaType.APPLICATION_JSON_TYPE);
User user = webResource.get(User.class);
Is this even possible or I have to implement full JSON structure in Java Beans to get it work?
I know that I can parse this JSON with Jackson and any other methods.
With Jackson, easiest way is to configure ObjectMapper like so:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Check this sample provider
package com.company.rest.jersey;
#Provider
#Component
#Produces({MediaType.APPLICATION_JSON})
public class JacksonMapperProvider implements ContextResolver<ObjectMapper> {
ObjectMapper mapper;
public JacksonMapperProvider(){
mapper = new ObjectMapper();
mapper.configure(Feature.INDENT_OUTPUT, true);
// Serialize dates using ISO8601 format
// Jackson uses timestamps by default, so use StdDateFormat to get ISO8601
mapper.getSerializationConfig().setDateFormat(new StdDateFormat());
// Deserialize dates using ISO8601 format
// MilliDateFormat simply adds milliseconds to string if missing so it will parse
mapper.getDeserializationConfig().setDateFormat(new MilliDateFormat());
// Prevent exceptions from being thrown for unknown properties
mapper.configure(
DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
#Override
public ObjectMapper getContext(Class<?> aClass) {
return mapper;
}
}
With Jackson :
You have two options:
Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
Or, you can use the #JsonIgnore annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.
#JsonIgnore
public int getSecurityCode(){
return securityCode;
}
In your bean, add the annotation #JsonIgnoreProperties(ignoreUnknown = true) at the class level and it should skip the id property in the JSON since it's not present in the bean.
#JsonIgnoreProperties(ignoreUnknown = true)
public class User{
private String name;
//getter & setter
}
(See http://wiki.fasterxml.com/JacksonAnnotations for details)

Categories

Resources