Spring Boot JSON Serialization - json

I'm using Spring Boot 1.3.3 and created a REST controller to add a JSON object into Mongo DB collections.
The data to be added from the JSON object will be a subset of information received from the request. So i have created a JSON request object ( DTO ) and an entity object ( model ) to be stored in Mongo collection.
I'm facing an issue now as the JSON request object is populated with default values for integer ( 0 ) and boolean data types ( false ) even if these fields are not populated as part of the request message. I don't want to store these values in the database.
I have added " spring.jackson.serialization-inclusion=non-null " and " spring.jackson.serialization-inclusion=non-default " properties in my application.properties file but still the fields are populated with default values.
Could anyone please help me out in resolving this issue and bypass the default values. NOTE: It works fine for String data type as they would be NULL values by default if not created.
Thanks in advance

String Attributes accept the null value while the primitive attributes have a default value for example 0 is default value for the int attributes.. to avoid having this values Use Integer instead.

Please use this annotation above your fields in bean class with which you facing the problem and tell me your problem is solved.
'#JsonInclude(Include.NON_NULL)'
Thanks

Related

JSONObject how to store null value

I am using com.liferay.portal.kernel.json.JSONObject in liferay 6.2 and I want to store null value in an object of this type as mentioned below
`JSONObject jsonObject = JSONFactoryUtil.createJSONObject();`
`jsonObject.put("name","varun")`
`jsonObject.put("address",null)`
As in org.json.JSONObject we can set null by JSONObject.NULL
Is there any way to set null in liferay JSONObject?
The Liferay object wraps only the com.liferay.portal.json.JSONObjectImpl
As Tobias said you can use the JSONObject.NULL
Another thing is, do you really need to set this? Usually, parsers just null the fields if they don't find them.

Alternate solution to save as JSON datatype in postgres spring-boot + eclipselink

I am using eclipselink 2.6 with spring-boot JPA for persistance in postgres.
I am persisting a List of objects as a JSON column in database.Acording to this solution: eclipselink + #convert(json) + postgres + list property
I am able to save the data in postgres.
When the column is null, I get this exception:
Caused by: org.postgresql.util.PSQLException: ERROR: column "sample_column" is of type json but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
I can solve this issue by this answer:
Writing to JSON column of Postgres database using Spring / JPA
Q1: Is there an alternate solution other than setting this property stringtype=unspecified int url spring.datasource.url=jdbc:postgresql://localhost:5432/dbnam‌​e?stringtype=unspeci‌​fied
Q2: If not, How can I set stringtype=unspecified in application.prooerties of spring-boot rather than embedding it in the spring.datasource.url
The answer is yes, but is implementation-specific.
For example, in Tomcat, this attribute is called connectionProperties, you would therefore write:
spring.datasource.tomcat.connection-properties: stringtype=unspecified
From the Spring-Boot documentation.
It is also possible to fine-tune implementation-specific settings using their respective prefix (spring.datasource.tomcat., spring.datasource.hikari., spring.datasource.dbcp.* and spring.datasource.dbcp2.*). Refer to the documentation of the connection pool implementation you are using for more details.
If you are using spring-boot 1.4.1 or above,
add a data.sql file in resources folder,
-- IN H2 database, create a column as 'OTHER' data type,
-- if H2 fails to create a column as 'JSON' data type.
CREATE DOMAIN IF NOT EXISTS JSON AS OTHER;
This .sql file will be executed during startup of your application and will create a column with data type others in table for the 'json' data type columns in H2 database.

ZF2 + Doctrine Entity - return query as array with datetime object?

I'm trying to output some data retrieved from a querybuilder query into a Datatables table with AJAX. I have my Zend Framework 2 controller and action setup to return a new JsonModel, which works fine.
However, one of the fields in my Entity is a datetime field, so Doctrine automatically returns it as a Datetime object, which is causing problems parsing the JSON response for Datatables. See sample JSON below:
{"aaData":[{"rSerial":"345gsdf","rPin":"76","rValue":633,"rDatetime":{"date":"2013-12-18 09:24:19","timezone_type":3,"timezone":"Europe\/London"}}],"success":true}
Is there a way that I can return the rDatetime column formatted as a string at the point the results are retrieved, to save me having to loop through and change it's format in the array of results?
$results = $queryBuilder->getQuery()->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
There actually seems to be a bug report for this issue with a supposed fix here
So I assume you can use the scalar hydration
Returns a flat rectangular result set instead of an object graph you can use scalar hydration
So your query would just need
$query = $queryBuilder->getQuery();
$results = $query->getResult(Query::HYDRATE_SCALAR);

How to pass empty or null date in JSON for WCF REST Web service

We have JSON object as follows.
{
"AdvanceNotificationDays":null,
"Egos":[],
"Interests":[],
"Name":"Birthday gift for Ruchir",
"Occasion":null,
"OccasionDate":"\/Date(null)\/",
"ProfileId":null,
"UserId":4350,
"WishlistId":0,
"isShared":false
}
We try to pass this JSON object to the server and everything gets parsed except the Date. For date, the JSON parser throws the exception that says "Cannot parse null to Int64". We just want to pass empty date or null date to the server. Can anybody please help? We googled for solution to this issue, did not find an answer so far.
Why don't you just set OccasionDate to null?
try making OccasionDate of type DateTime? so the date can be null.

mysql datetime mapped to JPA Temporal.Type TIMESTAMP. Getting only date, no time in JSON response

Here is scenario.
I have a JPA entity class with the field
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_DATE", length = 19)
private Date createdDate = null;
And this field is mapped to a column CREATED_DATE with the type datetime (i am using mysql) in a Table.
When I select the rows of the table, CREATED_DATE column shows the Date and Time both. When I fetch the row data using query.getSingleResult and typecast the returned object to the Entity class, the createdDate field of the entity class also has both Date and Time :
request = (MyEntityClass) query.getSingleResult();<br>
System.out.println(request.getCreatedDate());
prints 2012-05-18 06:32:57.0 in the catalina.out log.
Now I am sending this Entity Class object to a particular client request as a Json object. The Json response the client receives though, when printed, does not show date time, it shows only date:
ClientResponse<String> response = clientRequest.get(String.class);
System.out.println("Response getResource ::"+response.getStatus()+"::"+response.getEntity());
console output:
Response getResource ::200::[{ ....... ,"createdDate":"18-05-2012", ......}]
I am using RestEasy Json api at the server side.
I have seen a similar question ( similar SO post) in SO, but the answer discussed there doesn't seem to work with me.
Please help.
The problem is related to the way the object is serialized to JSON. You probably configured it in one way or another (annotation, default implementation, config file) so that dates are serialized this way.