I have an object named Item with plenty of fields. I'm using a Java JSON (json-io) library to serialize its state in a File:
String json = JsonWriter.objectToJson(item);
// Write String to File
I'd like to make the json String less verbose so that it does not include null values (if possible also boolean which are false). Is it possible to do it somehow ?
Thanks
I can recommend using jackson mapper if possible.
Check out these two questions:
Jackson serialization: ignore empty values (or null)
How to tell Jackson to ignore a field during serialization if its value is null?
Related
I want to serialize an object to JSON and ignore empty fields. for that I used
objectMapper
.setSerializationInclusion(Include.NON_NULL)
.setSerializationInclusion(Include.NON_EMPTY)
now I want the opposite way.
to be able to deserialize it back to object but without null but empty values.
using the mapper object.
I don't want to touch the class itself and I want it to work for any kind of class (to be generic).
is it possible?
Thanks.
I need to convert a certain JSON string to a Java object. I am using Jackson ObjectMapper for reading the JSON. The JSON String is something like this:-
"{"emailId":"gmail#rajnikant.com","accessToken":"accTok"}4".
When I am using objectMapper.readValue() for reading the JSON string to a specific destination class, it should throw an exception because of the JSON string being appended by 4. What should I do so that only valid JSON can be read and in other cases it will throw an exception?
To Jackson, GSON and others, a JSON string with some characters appended after the last } is valid JSON as long as what is contained between the {} is valid JSON.
As stated by a member of FasterXML (Jackson) team:
Yes. This is by design. If you want to catch such problems, you need to construct JsonParser, advance it manually. Existence of multiple root-level values is not considered a validity problem.
Reference: https://github.com/FasterXML/jackson-databind/issues/726
So if you need to enforce "clean" JSON you'll have to extend the default parser with your own functionality. However, IMO if it's OK to the default parser it should be OK to you too (unless we're dealing with some inter-language incompatibility scenario here).
As far as I know, all JSON field names are string values. However, I encountered a code snippet that does a string check on the "keys" of JSON to see if it's a string, and if not, it throws an exception. It goes something like:
if (!(key instanceof String)){
throw new exception();}
Is this check necessary?
EDIT:
For example,
while (jp.nextToken() == JsonToken.FIELD_NAME){
String key = jp.getCurrentName();
}
This code snippet will only progress to JSON tokens that are strings, so I was wondering if a JSON could contain fieldnames that are not strings so that Jackson parser will simply skip those fieldnames.
From the JSON official website (and by proxy, the JSON Data Interchange Standard):
When creating an object, the key must be a String.
EDIT: As #SotiriosDelimanolis pointed out in the comments, this only applies to the format of the JSON file, not necessarily once parsed through a Java library.
Jackson, for example, can deserialize keys into custom types - #SotiriosDelimanolis
I have trivial object serialization via Jackson library:
ObjectMapper objectMapper = new ObjectMapper();
String jsonText = objectMapper.writeValueAsString(myComplexObject);
I have one field in myComplexObject that I sometimes do not want to edn up in serialized result. I know that I can avoid serialization completely if I declare a field in myComplexObject with #JsonIgnore, but I need that field sometimes present in the JSON. Can I achieve this effect? I can assign that field to NULL or to some other special value in case I do not need it.
Quite a few ways, from simple JSON Views to #JsonFilter, explained at "Every day Jackson usage, part 3: Filtering properties" (and its followup, "Advanced filtering with Jackson, Json Filters")
I use the Jackson library with Java to serialize POJOs to JSON and vice versa. Let's say that I am running some tests where I am serializing an object and I know that the expected JSON string is {"firstName":"John", "lastName":"Doe"}. What is the best way to validate that my object serialized to the above string? Or better yet, what is the best way to validate that each of the fields is what I expect?
I have tried simply hard coding that string in and doing a comparison, but I have had cases where I serialize to JSON -> deserialize to POJO -> then serialize the deserialized POJO back to JSON again, and the fields are out of order. Then the string comparison fails even though all of the fields are correct.
Is there are better/different way to verify that my JSON string has the expected fields in it when testing?
I ran into the exact same situation as you and found JSONassert to be very helpful.
In your JUnit test you would have to add something like this:
String actual = getSerializedContent();
String expected = "{firstName:\"John\", lastName:\"Doe\"}";
JSONAssert.assertEquals(expected, actual, false);