FastJSON自定义序列化-修改属性值

前端之家收集整理的这篇文章主要介绍了FastJSON自定义序列化-修改属性值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简介

SerializeFilter是通过编程扩展的方式定制序列化。fastjson支持6种SerializeFilter,用于不同场景的定制序列化。

PropertyPreFilter 根据PropertyName判断是否序列化
PropertyFilter 根据PropertyName和PropertyValue来判断是否序列化
NameFilter 修改Key,如果需要修改Key,process返回值则可
ValueFilter 修改Value
BeforeFilter 序列化时在最前添加内容
AfterFilter 序列化时在最后添加内容

修改属性

以下示例将name为“Jack”改为“Foo”.

  1. public class TestFastJson(){
  2. @Test
  3. @Ignore
  4. public void testJSON(){
  5. Person person = new Person(22,"Jack");
  6.  
  7. ValueFilter valueFilter = new ValueFilter() {
  8. @Override
  9. public Object process(Object o,String propertyName,Object propertyValue) {
  10. if(propertyName.equals("name")){
  11. return new String("Foo"); //返回修改后的属性值对象
  12. }
  13.  
  14. return propertyValue;
  15. }
  16. };
  17.  
  18. String jsonString = JSON.toJSONString(person,valueFilter);
  19. System.out.println("jsonString is: " + jsonString);
  20.  
  21. }
  22.  
  23. private static class Person{
  24. int age;
  25. String name;
  26. private Person(int age,String name){
  27. this.age = age;
  28. this.name = name;
  29. }
  30. public int getAge() {
  31. return age;
  32. }
  33.  
  34. public void setAge(int age) {
  35. this.age = age;
  36. }
  37.  
  38. public String getName() {
  39. return name;
  40. }
  41.  
  42. public void setName(String name) {
  43. this.name = name;
  44. }
  45. }

猜你在找的Json相关文章