import java.util.Arrays;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonTest {
public static void main(String[] args) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(User.class, new JsonValueProcessor() {
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
User u=(User)value;
return String.format("{\"id\":'%d',\"name\":\"%s\"}",u.getUserid(),u.getUsername());
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return value;
}
});
User user=new User();
user.setUserid(123);
user.setUsername("json-lib");
List<User> users=Arrays.asList(user);
String data=JSONArray.fromObject(users,jsonConfig).toString();
System.out.println(data);
}
}
class User{
private int userid;
private String username;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Json lib JsonConfig用法
最新推荐文章于 2019-05-23 17:05:03 发布