首页 > Java > java教程 > 正文

我们如何使用Java中的flexjson将对象数组序列化?

王林
发布: 2023-08-26 09:21:21
转载
1385 人浏览过

我们如何使用Java中的flexjson将对象数组序列化?

Flexjson是一个轻量级库,用于将序列化反序列化Java对象与JSON格式。我们还可以使用JSONSerializer类的 serialize()方法序列化对象数组,这会执行目标实例的浅序列化。

语法

public String serialize(Object target)
登录后复制

在下面的程序中,我们需要序列化一个数组对象.

示例

import flexjson.JSONSerializer;
public class JsonSerializeArrayTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
      Student stud1 = new Student("Adithya", "Sai", 28, "Hyderabad");
      Student stud2 = new Student("Jai", "Dev", 30, "Chennai");
      Student stud3 = new Student("Ravi", "Chandra", 35, "Pune");
      Student[] students = {stud1, stud2, stud3};
      String jsonStr = serializer.serialize(students);
      System.out.println(jsonStr);
   }
}
// Student class<strong>
</strong>class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Student() {}
   public Student(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public String getAddress() {
      return address;
   }
   public String toString() {
      return "Student[ " +
      "firstName = " + firstName +
      ", lastName = " + lastName +
      ", age = " + age +
      ", address = " + address +
      " ]";
   }
}
登录后复制

输出

[
 {
 "address": "Hyderabad",
 "age": 28,
 "class": "Student",
 "firstName": "Adithya",
 "lastName": "Sai"
 },
 {
 "address": "Chennai",
 "age": 30,
 "class": "Student",
 "firstName": "Jai",
 "lastName": "Dev"
 },
 {
 "address": "Pune",
 "age": 35,
 "class": "Student",
 "firstName": "Ravi",
 "lastName": "Chandra"
 }
]
登录后复制

以上是我们如何使用Java中的flexjson将对象数组序列化?的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板