We usually have a JSON string and Java objects in the mutual transfer, often selectively filtered out some of the property values, and the Json-lib package Jsonconfig provides us with this functionality, the implementation of the following methods. (1) Set up the Jsonconfig instance and configure the attribute exclusion list, (2) write a custom jsonbeanprocessor with the attribute filter and (3).
1. How to implement the Jsonstring interface
public class Person implements jsonstring {
private String name;
Private String LastName;
private address address;
Getters & Setters
Public String tojsonstring () {
Return "{name: '" +name+ "', LastName: '" +lastname+ "'}";
}
}
2. The second method makes it easy to add or remove attributes that contain and need to be excluded through Jsonconfig instances
public class Person {
private String name;
Private String LastName;
private address address;
Getters & Setters
}
jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setexclusions (New string[]{"Address"});
Person bean = new Person ("Jack", "Li");
JSON json = Jsonserializer.tojson (bean, jsonconfig);
3. Using PropertyFilter allows you to control both properties and classes that need to be excluded, which can also be bidirectional or applied to JSON strings to Java objects
public class Person {
private String name;
Private String LastName;
private address address;
Getters & Setters
}
Jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.setjsonpropertyfilter (New PropertyFilter () {
public Boolean apply (object source/* Property owner * /, String name/* Property name */, Object value/* Property value * /) {
Return true to skip name
return source instanceof person && name.equals ("address");
}
});
Person bean = new Person ("Jack", "Li");
JSON json = Jsonserializer.tojson (bean, jsonconfig)
4. Finally look at Jsonbeanprocessor, which is similar to the implementation of jsonstring, returning a legitimate jsonobject representing the original domain class
public class Person {
private String name;
Private String LastName;
private address address;
Getters & Setters
}
jsonconfig jsonconfig = new Jsonconfig ();
Jsonconfig.registerjsonbeanprocessor (Person.class, New Jsonbeanprocessor () {
Public Jsonobject Processbean (Object Bean, Jsonconfig jsonconfig) {
if (! ( Bean instanceof Person) {
return new Jsonobject (true);
}
Person person = (person) bean;
return new Jsonobject (). Element ("name", Person.getname ()). Element ("LastName", Person.getlastname ());
}
});
Person bean = new Person ("Jack", "Li");
JSON json = Jsonserializer.tojson (bean, jsonconfig);
JSON complex object Processing Jsonconfig