I'm thinking of using the XStream library but I have a couple of questions/concerns.
Say I have a complex object that I want to serialize into XML (or JSON) using XStream. Is XStream able to handle this without any extra work?
For example:
class Foo
{
private Bar bar;
private string name;
// Getters and Setters
}
class Bar
{
private Integer id;
private string name;
// getters and setters
}
Can XStream handle this correctly? Thanks!
Short answer: Yes, it can.
But will do it with a lot of reflection overhead. I wouldn't write such code in production release.
Also, keep in mind that you have to look for bi-directional reference which will cause a runtime exception.
Yes, simple nested structures (references to other objects, lists and maps) are supported.
Things get hairy if you need to access fields from different levels (say, you need an attribute from <foo> in Bar).
Related
I've been searching around but haven't been able to find a good example of this. I have a POJO such as
public class SomeObject implements Serializable {
private String name;
private String residence;
private String phone;
// standard getters and setters
}
I am trying to find a better, more dynamic way using reflection to find if any of those attributes contain empty strings e.g. "", and set those attributes to null. I know I could manually loop through the object and look at each attribute individually and set it that way, but I figure there has to be a better programmatic solution than that. Would anyone be able to help me with this?
We use JSON serialization with Jackson to expose internal state of the system for debugging properties.
By default jackson does not serialize transient fields - but I wish to serialize them as well.
How can I serialize these fields?
One way I know is to supply a getters for these fields - but I don't want to do that, as I have some getX methods that I don't want to be invoked ( for instance, there are some getters that change the objects state ).
I know I could create an annotation, but I really want to avoid it.
So my question is:
Is there a way to setup jackson to serialize all the objects fields? include transient ones.
My solution with Jackson 2.4.3:
private static final ObjectMapper mapper =
new ObjectMapper(){{
Hibernate4Module module = new Hibernate4Module();
module.disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
registerModule(module);
}};
I don't think Jackson supports any type of configuration to enable it to serialize a transient field. There's an open issue to add that feature, but it's old and hasn't been addressed (as far as I can tell): http://jira.codehaus.org/browse/JACKSON-623
So my question is: Is there a way to setup jackson to serialize all
the objects fields? include transient ones.
So to answer your question, no.
Some other Java JSON tools, such as GSON do support a configuration option to serialize transient fields. If you can use another tool, you might look into that (for GSON, see: https://sites.google.com/site/gson/gson-user-guide).
To expand a little, you might try a different approach.
First, You shouldn't try to serialize a transient field. After all the definition of transient is "don't serialize this." Nevertheless I can think of a few specific situations where it might be necessary, or at least convenient (like when working with code you can't modify or such). Still, in 99% of cases, the answer is don't do that. Change the field so that it's not transient if you need to serialize it. If you have multiple contexts where you use the same field, and you want it serialized in one (JSON, for example), and not serialized in another (java.io, for example) then you should create a custom serializer for the case where you don't want it, rather than abuse the keyword.
Second, as to using a getter and having "some getters that change the objects state," you should try to avoid that too. That can lead to various unintended consequences. And, technically, that's not a getter, that's a setter. What I mean is, if it mutates state, you've got a mutator (setter) rather than accessor (getter), even if you name it following the "get" convention and return some stuff.
You can create a custom getter for that transient field and use #XmlElement attribute. It doesn´t matter the name of that getter.
For example:
public class Person {
#XmlTransient private String lastname;
#XmlElement(name="lastname")
public String getAnyNameOfMethod(){
return lastname;
}
}
Another way to let Jackson serialize property is to add #JsonProperty annotation above it.
I guess it's better approach cause you do not need to disable default behaviour for all #Transient fields, like in Gere's answer.
So my goal is to return some objects as the response body from a Spring REST controller. The thing is, these two objects point each other, something kind of like this:
public class Person {
private Set<Team> teams;
}
public class Team {
private Set<Person> members;
}
If I return these two objects from a controllers mapping method right away, the generated response will be infinite and will probably crash the browser, because the members set has people, and each person has a set of teams, and so on, and everything gets returned infinitely.
How can I manage, instead of showing the whole list of, say, members, to display just the name of each of the members?
Any help will be much appreciated, thanks!
If you are using jackson then you must use jackson provided solution to problem you are mentioning.
#JsonManagedReference
#JsonBackReference
Also look at this link which might be helpful :
Infinite Recursion with Jackson JSON and Hibernate JPA issue,
Also
https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations#object-references-identity
This question already has answers here:
Java Getters and Setters
(17 answers)
Closed 9 years ago.
My Java is a bit rusty (been doing C# for the last couple of years). Also I hope this won't be a very subjective question.
Anyway say I had class Person (yeah a bit of a cliche, I know), with no behaviour (C# version):
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// say 10+ properties
}
How would the equivalent Java version look like ?
I know I can write bunch of getters and setters (but say I had 10+ properties), it feels like a lot of boilerplate.
Is it considered bad practice to just do:
public class Person {
public String name;
public int age;
// rest of the stuff here
}
I feel a bit uneasy about this. I realise there is no "right answer" but, I'm more interested in the general conventions and best practices.
You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation. Also maybe you need just a getter.
Another advantage of using a getter or setter can be doing some checks or preprocessing before returning or setting the field.
Here is a sample code snippet:
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
Optionally you can use http://projectlombok.org/ and write it like this using annotations:
#Getter #Setter
private String name;
The code generation is done compile time.
It's better to have getter/setters to return the fields so that you can encapsulate the way the fields are calculated. Although it happens rarely, there may come a time when you want to change something like this:
getBalance()
{
return this.staticBalance;
}
to this:
getBalance()
{
return calculateBalance();
}
And the only way in Java to change field behavior without potentially changing tons of code (or worse requiring your API users to change bunches of code) is to use getters and setters.
Other benefits are:
Ability for subclasses to override the behavior
Improved thread safety because you can synchronize access
Writing the boilerplate is tedious, but a good IDE will just generate those methods for you from the field names.
You have to create manual functions to do it.
So first, you create a backing field.
private String _backingString
Then you create getters and mutators
public String getBackingString()
{
return this._backingString;
}
public String setBackingString(String value)
{
this._backingString = value;
}
It's the Java convention - there's no other way around it. However, you'll be pleased to know most IDEs have tools to generate these. Just google around for your favourite IDEs generator tool.
You can see this SO question on how to do this in Eclipse.
You should do getters and setters for each. Modern IDE's make it easy because they have auto-insert option.
Eventually you can create get and set methods in Calendar's class style.
I often use both approaches, having getters and setters and not. I always use private fields which force the use of getters and setters in my model. Using JPA and Hibernate my model is tied to my DB schema. Then for my DTOs which are normally used for things like RESTful services I use mostly public fields with no getters and setters. These DTOs have no logic and get marshaled out to JSON or created from JSON that's being set from a client so I find no need for the getters and setters. I usually don't end up override equals and hashCode for these too. They are as simple as possible.
So I don't think there's a right or wrong way and it depends on usage.
And if you are going to create you getters and setters let your IDE do the work for you.
Which IDE are you using? In Eclipse you can create them automatically from the source menu, and their names are derived from the field names.
Code:
private String myField;
public String getMyField()
{
return this.myField;
}
public void setMyField(String value)
{
//validation stuff
this.myField = value;
}
I'm trying to deserialize JSON Object coming from an application I can't control. Here my JSON :
{"assembly":
{"name":"mm9",
"id":32,
"chromosomes":[
{"chromosome":
{"name":"MT"}
}]}}
My Pojos, are
class Assembly{
private String name;
private int id;
private ArrayList<Chromosome> chromosomes;
// getters & setters
}
class Chromosome {
private String name;
//getter/setters
}
But it's not working because of the extra fields "assembly" & "chromosome", so with a JSON like :
{"name":"mm9",
"id":32,
"chromosomes":[
{"name":"MT"}
] }}
it simply working.
Is there a way to modify configuration or something to achieve this without create more complex POJOS?
The problem is that in the first JSON snippet, chromosomes is a dictionary (Map), of which one of the entries (chromosome) happens to correspond to your Chromosome object.
A more accurate direct mapping to a Java class would be
class Assembly{
...
private Map<String, Chromosome> chromosomes;
}
Since you mention you can't control the format of the source JSON, you may want to look into using custom deserializers, or perhaps using the streaming support from Jackson rather than ObjectMapper for direct mapping, if you aren't happy changing your POJOs in this way.
By the way, it is best to refer to collections by their interface type (List) rather than a concrete type (ArrayList). It is very unlikely that code that refers to this class truly cares or needs to know that it is using an ArrayList, referring to just the List interface instead makes it a lot easier to swap other implementations in if needed (as a general principle).