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

2023年 8月 28日 62.7k 0

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

Syntax

public String serialize(Object target)

登录后复制

In the below program, we need to serialize an array of objects.

Example

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
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将对象数组序列化?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论