How to exclude certain attributes from being serialized - java

This question has been asked multiple time, I have a Java POJO class which I would like to serialize by excluding some attributes. In order to do this, I am using #Expose from GSON. The problem is that it does not seem to work.
Even if I use this: Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
It does not work.
I am reluctant to use transient because it disables both serialization and deserialization of the given attribute.

you can use transient
private transient String property;

Make sure you initialize your Gson object properly. You should call excludeFieldsWithoutExposeAnnotation method in your GsonBuilder if you want to use the Exclude annotation.
For example
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson javadoc description of excludeFieldsWithoutExposeAnnotation

Related

Serialize vertx JsonObject using Jackson

I'm using vertx and Jackson in my development. In one of my classes, I got a field of type JsonObject, something like this:
class User
private String name;
private JsonObject details;
This details field can contain other JsonObjects or JsonArrays, e.g.:
{"details": [{"street": "Broadway"}, {"building": 20}]}
I don't have a dedicated class of this structure, as far as there's no fixed structure and it can vary.
details object is being created in the way like this:
JsonObject details = new JsonObject().put("name", "value").put("another", "another")
This aproach allows me to store details of any structure inside my code. As far as I don't need to manipulate this data on my backend, I don't want to create a special structure for it.
Everything works fine until I'm trying to serialize this JsonObject using Jackson. Unfortunately, instead of beatiful JSON string, Jackson gives me map object serialized with all map's additional fields.
How can I serialize JsonObject of vertx using Jackson?
Looking at JsonObject's javadoc , I saw a getMap() method. I know Jackson is capable of serializing Maps with ease.
Finally, it turned out that vertx already has it's own implementation of Serializer.
It's enough just to use theirs class to perform serialization (which will use Jackson undercover).
JsonObject user = new JsonObject(Json.encode(new User());
And it works fine.
I would suggest creating using https://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.7.3/com/fasterxml/jackson/databind/ObjectMapper.html#convertValue(java.lang.Object,%20java.lang.Class) like this:
new JsonObject((Map)Json.mapper.convertValue(new User(), Map.class));
Converting to and from String takes time.

How to parse json with java language keywords

Is there away to parse json with java keywords like class, case, default etc. to java object using Gson library?
The lines
Gson gson = new Gson();
MyObject myObject = gson.fromJson(json, MyObject.class);
simply parse json to my pojo, but I have key "class" in my json and I can't use the field "class" in java classes.
Yes, annotate your fields with #SerializedName, specifying the name of the field.
#SerializedName("class")
private String classField;
Or use a custom TypeAdapter.
You have to use annotations. These annotations tell Gson which JSON field maps to which Java property:
http://www.javacreed.com/gson-annotations-example/

How can I prevent gson to try to parse value of my variable? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Recently I've got an interesting problem with getting json string out of the object using gson library.
My object has a simple form:
class MyObject{
public String myString = "{\"payload\":\"test\"}";
setters & getters
}
The value of myString is a json string.
So when I'm trying to use
MyObject myObject = new myObject();
Gson gson = new Gson();
String payload = gson.toJson(myObject);
I got an exception saying:
Failed to process Expression Evaluation "json:payload".
So it looks like gson is trying to parse the value of the field in myObject, which is unexpected and weird.
How can I prevent gson to try to parse value of my variable?
Thanks,
Laura.
The following code
public static void main(String[] args) {
MyObject original = new MyObject();
Gson gson = new Gson();
String payload = gson.toJson(original); // generate json
System.out.println(payload);
MyObject recreated = gson.fromJson(payload, MyObject.class); // parse json
System.out.println(recreated.myString);
}
static class MyObject {
public String myString = "{\"payload\":\"test\"}";
}
prints
{"myString":"{\"payload\":\"test\"}"}
{"payload":"test"}
So I don't see what you're worried about. I get no errors.
How can I prevent gson to try to parse value of my variable?
Do you want the value of myString in the generated json or not?
If a field is marked transient, it is ignored and not included in the JSON.
Gson can do this in a few ways, marking a field transient, using a custom DeserializationExclusionStrategy and usage of the #Expose annotation (although this annotation is the inverse of your use case)
That being said, your example case seems like it works fine.
see the section on the user guide. Full of useful stuff!
https://sites.google.com/site/gson/gson-user-guide
Excluding Fields From Serialization and Deserialization
Gson supports numerous mechanisms for excluding top-level classes,
fields and field types. Below are pluggable mechanism that allow
field and class exclusion. If none of the below mechanism satisfy your
needs then you can always use custom serializers and deserializers.
Java Modifier Exclusion
By default, if you mark a field as transient, it will be excluded. As
well, if a field is marked as "static" then by default it will be
excluded. If you want to include some transient fields then you can do
the following:
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifier(Modifier.STATIC)
.create();
NOTE: you can use any number of the Modifier constants to
"excludeFieldsWithModifier" method. For example: Gson gson = new
GsonBuilder()
.excludeFieldsWithModifier(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
.create(); Gson's #Expose
This feature provides a way where you can mark certain fields of your
objects to be excluded for consideration for serialization and
deserialization to JSON. To use this annotation, you must create Gson
by using new
GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The
Gson instance created will exclude all fields in a class that are not
marked with #Expose annotation.

Jackson JSON generator creates null JSON values for missing objects

I've started using Jackson as a JSON generator, as an alternative to google GSON. I've run into an issue where Jackson is generating object: null if the object is indeed null. GSON on the other hand generates NO entry in JSON, which is the behavior I want. Is there a way to stop Jackson from generating null object/value when an object is missing?
Jackson
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, some_complex_object);
String jackson = sw.getBuffer().toString();
System.out.println("********************* START JACKSON JSON ****************************");
System.out.println(jackson);
System.out.println("********************* END JACKSON JSON ****************************");
generates this:
{"eatwithrustyspoon":{"urlList":null,"device":"iPad","os":"iPhone OS","peer_id":
and GSON looks like this:
Gson gson = new Gson();
String json = gson.toJson(some_complex_object);
System.out.println("********************* START GSON JSON ****************************");
System.out.println(json);
System.out.println("********************* END GSON JSON ****************************");
and it generates this (which is what I want - note that "urlList":null was not generated) :
{"eatwithrustyspoon":{"device":"iPad","os":"iPhone OS","peer_id"
From the Jackson FAQ:
Can I omit writing of Bean properties with null value? ("how to prevent writing of null properties", "how to suppress null values")
Yes. As per JacksonAnnotationSerializeNulls, you can use:
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// or (for older versions):
objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false);
and voila, no more null values. Note that you MUST configure mapper before beans are serialized, since this setting may be cached along with serializers. So setting it too late might prevent change from taking effect.
my issue was bit different actually i was getting Null values for the properties of POJO class.
however i solved the problem by giving mapping to properties in my pojo class like this :
#JsonProperty("PROPERTY_NAME")
thought it may help someone :)
The following solution saved me.
objectMapper.setSerializationInclusion(Include.NON_NULL);

What is the most suitable Java data structure for representing JSON?

I' m developing a RESTful Android mobile client. Information exchange between my app and server is in JSON. So I' m now a little bit confused what data structure choose for represent JSON responses and data because there a lot of them. I've just stopped with LinkedHashMap<> but as far as i know JSON is unordered. Across the Internet I saw people use Map<> or HashMap<> for this. So the question - what is the best data structure for this purpose? Or if there is no a univocal answer - pros and cons of using data structures I' ve mentioned.
I would disagree with the first answer. The REST paradigm was developed so that you would operate with objects, rather than operations.
For me the most sensible approach will be if you declare beans on the client side and parse the json responses and request through them. I would recommend using the GSON library for the serialization/ deserialization. JsonObject/ JsonArray is almost never the best choice.
Maybe if you give examples of the operations you are about to use we might be able to help more precisely.
EDIT: Let me also give a few GSON Examples. Let's use this thread to compare the different libraries.
In the most cases REST services communicate objects. Let's assume you make a post of product, which has reference to shop.
{ "name": "Bread",
"price": 0.78,
"produced": "08-12-2012 14:34",
"shop": {
"name": "neighbourhood bakery"
}
}
Then if you declare the following beans:
public class Product {
private String name;
private double price;
private Date produced;
private Shop shop;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
public class Shop {
private String name;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
You can deserialize the json using:
String jsonString; // initialized as you can
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
Product product = gson.fromJson(jsonString, Product.class);
// Do whatever you want with the object it has its fields loaded from the json
On the other hand you can serialize to json even more easily:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
String jsonString = gson.toJson(product);
Are you talking about receiving and parsing the JSON string from a server request?
For that you can use:
import org.json.JSONArray;
import org.json.JSONObject;
Using these, I read through my JSON array from my POST request and store the resulting information in Class objects in my project.
For each item in JSONArray, you can extract the JSONObject and attributes like this:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.getString("text");
}
As far as actually storing the data, like mentioned above, JSON data can come in a wide array of formats depending on the source, and as such, it is usually parsed on the client end and saved in your application Class objects for use. Or more generically, you could store the data using Map<String, Object>
This is easily the best answer I've seen:
https://dzone.com/articles/which-is-the-right-java-abstraction-for-json
Summary: there are three abstrations: pojos, maps and lists, and custom classes to represent objects, arrays, and primitives. There are advantages and disadvantages to each, with no clear winner.
Pojos have the biggest advantages, but you can't always use them. Use them if you can, and use the others if you must.
If you are doing anything other than the most simple mapping then you should use a full class structure. Create your class hierarchy as a mirror of the data structure in JSON and use Jackson to map the JSON directly to the class hierarchy using the ObjectMapper.
With this solution you don't have any casting of Object to Map or messing around with JSONObject or JSONArray and you don't have any multi-level map traversal in your code. You simply take the JSON string, feed it to the ObjectMapper, and get a your Object, which contains child objects (even collections) automatically mapped by the ObjectMapper.
I've used xstream to serialize JSON, in the following way:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("myAlias", MyClass.class); // requires a no argument constructor
System.out.println(xstream.toXML(product));
Ok, the gentleman in the comments wants a deserialization example, here you are:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.alias("myAlias", MyClass.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
Let me know if you need further assistance...

Categories

Resources