@XmlRootElement(name = "person")
public class Person {
@XmlAttribute
private int id;
@XmlElement
private String name;
}
public static void main(String[] args) throws JettisonException {
Person person = new Person();
person.setId(1);
person.setName("John");
JSONSerializer serializer = new JSONSerializer();
String json = serializer.serialize(person);
System.out.println(json);
}
json
{"@id":1,"name":"John"}
Person person = new Person();
person.setId(1);
person.setName("John");
JSONConfig config = new JSONConfig().setTypeHintsEnabled(true);
JSONSerializer serializer = new JSONSerializer(config);
String json = serializer.serialize(person);
System.out.println(json);
json
{"#type":"person","@id":1,"name":"John"}
public class LocalDateConverter implements Converter {
@Override
public boolean canConvert(Class type) {
return LocalDate.class.equals(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
LocalDate date = (LocalDate) source;
writer.setValue(date.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String value = reader.getValue();
return LocalDate.parse(value);
}
}
public static void main(String[] args) throws JettisonException {
Person person = new Person();
person.setId(1);
person.setName("John");
person.setBirthdate(LocalDate.of(1990, 1, 1));
JSONConfig config = new JSONConfig().setCustomConverter(new LocalDateConverter());
JSONSerializer serializer = new JSONSerializer(config);
String json = serializer.serialize(person);
System.out.println(json);
}
json
{"@id":1,"birthdate":"1990-01-01","name":"John"}
@XmlRootElement(name = "person")
public class Person {
@XmlAttribute
private int id;
@XmlElement
private String name;
@XStreamOmitField
private String password;
}
public static void main(String[] args) throws JettisonException {
Person person = new Person();
person.setId(1);
person.setName("John");
person.setPassword("123456");
JSONConfig config = new JSONConfig().setSkipFieldsWithoutExposeAnnotation(true);
JSONSerializer serializer = new JSONSerializer(config);
String json = serializer.serialize(person);
System.out.println(json);
}
json
{"@id":1,"name":"John"}