Fastjson基于BeanToArray模式实现JavaBean与JSON数组的映射

在默认情况下,Fastjson实现了JavaBean和JSON对象之间的映射。

此外,Fastjson还支持一种更精简的映射,可以实现JavaBean与JSON数组之间的映射。优点是序列化之后的JSON字符串更小,缺点是降低了可读性。

本篇内容基于Fastjson 1.2.62版本,马上开始学习吧。

默认的序列化方式

默认情况下,使用JSON.toJSONString序列化对象,转化为JSON对象字符串。

public class Animal {

    private String name;
    private int sex;
    private Integer weight;

    // 省略getter、setter方法
}
/**
 * 默认序列化
 */
@Test
public void toJSONString() {
    Animal animal = new Animal();
    animal.setName("sam");
    animal.setSex(1);
    animal.setWeight(100);

    System.out.println(JSON.toJSONString(animal));
}

执行结果:

{"name":"sam","sex":1,"weight":100}

实现JavaBean与JSON数组映射

JavaBean序列化为JSON数组

使用JSON.toJSONString进行序列化时,传入SerializerFeature.BeanToArray参数,启用从JavaBean到JSON数组的映射。

/**
 * 序列化时启用SerializerFeature.BeanToArray.<br>
 * 不序列化key,而是将value作为数组字符串输出,输出的json字符串更小,也节省了空间.<br>
 * 官方测试数据表示,启用后性能更好.
 */
@Test
public void toJSONStringWithBeanToArray() {
    Animal animal = new Animal();
    animal.setName("sam");
    animal.setSex(1);
    animal.setWeight(100);

    System.out.println(JSON.toJSONString(animal, SerializerFeature.BeanToArray));
}

执行结果:

["sam",1,100]

JSON数组反序列化为JavaBean

同样的,在反序列化的时候,传入Feature.SupportArrayToBean参数,启用将JSON数组反序列化为JavaBean。

/**
 * 反序列化时启用Feature.SupportArrayToBean.<br>
 * 支持将json数组反序列化为JavaBean.
 */
@Test
public void parseObjectWithBeanToArray() {
    String jsonString = "[\"sam\",1,100]";
    Animal animal = JSON.parseObject(jsonString, Animal.class, Feature.SupportArrayToBean);
    System.out.println(JSON.toJSONString(animal));
}

执行结果:

{"name":"sam","sex":1,"weight":100}

使用JSONType注解实现类级别映射

如果只需要针对特定的类进行映射,可以使用JSONType注解来实现。

public class ArticleList {

    private String name;
    private List<Article> articles;

    // 省略getter、setter方法
}

@JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
public class Article {

    private String title;
    private String content;

    // 省略getter、setter方法
}
/**
 * 在需要进行JSON数组映射的类,添加JSONType注解.
 */
@Test
public void toJSONStringWithJSONType() {
    List<Article> articles = new ArrayList<>();

    Article article = new Article();
    article.setTitle("title1");
    article.setContent("content1");
    articles.add(article);

    article = new Article();
    article.setTitle("title2");
    article.setContent("content2");
    articles.add(article);

    ArticleList articleList = new ArticleList();
    articleList.setName("name");
    articleList.setArticles(articles);

    // 序列化
    String jsonString = JSON.toJSONString(articleList);
    System.out.println(jsonString);

    // 反序列化
    ArticleList newArticleList = JSON.parseObject(jsonString, ArticleList.class);
    System.out.println(JSON.toJSONString(newArticleList));
}

执行结果:

{"articles":[["content1","title1"],["content2","title2"]],"name":"name"}
{"articles":[["content1","title1"],["content2","title2"]],"name":"name"}

使用JSONField注解实现字段级别映射

Fastjson还支持针对类的某个字段进行映射配置,使用JSONField注解进行声明。

public class AnimalParent {

    private String name;
    @JSONField(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
    private Animal animal;

    // 省略getter、setter方法
}
/**
 * 在需要进行JSON数组映射的字段,添加JSONField注解.
 */
@Test
public void toJSONStringWithJSONField() {
    Animal animal = new Animal();
    animal.setName("sam");
    animal.setSex(1);
    animal.setWeight(100);

    AnimalParent parent = new AnimalParent();
    parent.setName("parent");
    parent.setAnimal(animal);

    // 序列化
    String jsonString = JSON.toJSONString(parent);
    System.out.println(jsonString);

    // 反序列化
    AnimalParent newParent = JSON.parseObject(jsonString, AnimalParent.class);
    System.out.println(JSON.toJSONString(newParent));
}

执行结果:

{"animal":["sam",1,100],"name":"parent"}
{"animal":["sam",1,100],"name":"parent"}

小结

在普通模式下,序列化时JavaBean会映射成JSON对象。

Fastjson还支持一种叫做BeanToArray的映射模式,在该模式下,JavaBean将会映射为JSON数组。同时,JSON数组也可反序列化为JavaBean。

使用BeanToArray模式的优点是序列化之后的JSON字符串更小,节省空间,性能上也会有所提升。缺点是降低了可读性。

有3种方法可以启用BeanToArray模式:

1.在调用JSON类的序列化和反序列化方法时,传入启用BeanToArray模式的配置项;
2.为指定的类添加JSONType注解实现类级别映射;
3.为指定字段添加JSONField注解实现字段级别映射。

参考

《轻松学习Fastjson》

https://github.com/alibaba/fastjson

https://github.com/alibaba/fastjson/wiki/BeanToArray_en


---转载本站文章请注明作者和出处 996极客教程(996geek.com),请勿用于任何商业用途---

《Fastjson基于BeanToArray模式实现JavaBean与JSON数组的映射》有26条留言

  1. Hello there!
    This is my first visit to your blog! We are a team of volunteers and starting a new
    project in a community in the same
    niche. Your blog provided us beneficial information
    to work on. You have done a extraordinary job!

    回复
  2. My partner and I stumbled over here
    from a different web address and thought I
    may as well check things out.
    I like what I see so now I’m following you. Look forward
    to looking at your web page repeatedly.

    回复
  3. It’s perfect time to make some plans for the longer term and it’s time to be happy. I have read this put up and if I may I wish to suggest you some interesting issues or suggestions. Perhaps you can write next articles regarding this article. I want to learn even more issues about it!

    回复
  4. I am really enjoying the theme/design of
    your web
    site. Do you ever run into any browser compatibility issues?

    A few of my blog
    visitors have complained about my website not
    working correctly in Explorer but looks great in Opera.

    Do you have any ideas to help fix this problem?

    回复
  5. I do not know whether it’s just me or if perhaps
    everybody else experiencing issues with your blog. It
    appears as if some of the written text in your posts
    are running off the screen. Can somebody else please provide feedback
    and let me know if this is happening to them too?
    This may be a issue with my internet browser because
    I’ve had this happen before. Kudos

    回复
  6. I’m really enjoying the design and layout of your website.

    It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire
    out a designer to create your theme? Exceptional work!

    回复
  7. I know this if off topic but I’m looking into starting my own blog and was wondering what all is required to get set
    up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet savvy so I’m not 100% certain. Any tips or advice would
    be greatly appreciated. Appreciate it

    回复
  8. Awesome blog! Do you have any hints for aspiring writers?
    I’m planning to start my own website soon but I’m a little lost on everything.
    Would you propose starting with a free platform
    like WordPress or go for a paid option? There are so many options out there that I’m completely confused
    .. Any suggestions? Thanks!

    回复
  9. Hello, I think your web site could be having internet browser
    compatibility problems. Whenever I look at your site in Safari, it
    looks fine but when opening in IE, it’s got some overlapping
    issues. I merely wanted to give you a quick heads up!
    Besides that, excellent blog!

    回复
  10. Hey there just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Opera.
    I’m not sure if this is a format issue or something
    to do with internet browser compatibility but I figured I’d post to let you know.
    The design look great though! Hope you get the problem solved soon. Many thanks

    回复
  11. Oh my goodness! Incredible article dude! Thanks,
    However I am encountering problems with your RSS. I don’t understand why I cannot join it.
    Is there anyone else having the same RSS issues? Anyone
    that knows the solution will you kindly respond?
    Thanx!!

    回复
  12. Undeniably believe that which you stated. Your favorite justification appeared to be on the net the
    easiest thing to be aware of. I say to you, I certainly get annoyed
    while people think about worries that they plainly don’t know about.

    You managed to hit the nail upon the top and defined out the whole thing
    without having side-effects , people can take a signal. Will probably be back to get more.
    Thanks

    回复
  13. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment
    is added I get several emails with the same
    comment. Is there any way you can remove people from that service?

    Bless you!

    回复

留下评论