3

I'm using XStream parser. I wants to get an empty tag in place of null values for a variable. How do I achieve this?

Example:

class Person{
    private String name;
    private String age;
}

Person person = new Person("Joe", null);

I'm getting this,

<Person>
    <name>Joe</name>
</Person>

I need this,

<Person>
    <name>Joe</name>
    <age></age>
</Person>
Venkat Prasanna
  • 692
  • 4
  • 16

1 Answers1

0

If it only concerns strings, initialise them with "", not with null.

So instead of:

Person person = new Person("Joe", null);

Try:

Person person = new Person("Joe", "");

Also, make sure to take a look at: XStream serialize null values

Community
  • 1
  • 1
VinKel
  • 121
  • 7
  • If its two fields then its ok. I have 12 classes which has around 30 fields in each class aprox. I can't set to each variable. Is there any configuration for that whichever variable is null it should set an empty string like that? – Venkat Prasanna Jan 27 '17 at 09:07
  • Corry, couldn't really find/think of any other way... Maybe this [Correct way to represent null XML elements](http://stackoverflow.com/questions/774192/what-is-the-correct-way-to-represent-null-xml-elements) or this [XML serialization, hide null values](http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values) might help provide any help? – VinKel Jan 27 '17 at 09:32
  • Actually, what Saulius Next commented on your question seems to work, but that's the same solution as I have provided, but which looks neater. How about providing such default values in the getters and setters? Could you extend a bit on what your situation is? – VinKel Jan 27 '17 at 09:37