生成JSON数据--Gson(谷歌)方法

时间:2023-03-08 21:33:46

Gson生成JSON数据方法:

创建相应的类,然后创建对象,toJson()进去就可以了

要求:生成如下JSON数据

1.{“age”:4,”name”:”zhagnsan”}

2.{“no”:4,”name”:”zhangsan”,”employees”:[{“age”:3,”name”:”zhangsan”},{“age”:5,”name”:”lis”},{“age”:6,”name”:”wagw”}]}


第一题代码:

Person类

package com.qf.demo2;

public class Person {

    private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Person() {
super();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
} }

获得JSON数据

package com.qf.demo6;

import com.google.gson.Gson;
import com.qf.demo2.Person; public class Test { public static void main(String[] args) { Gson gson = new Gson(); Person person = new Person(4, "zhagnsan"); String json= gson.toJson(person);
System.out.println(json); }
}

第二题代码:

Person类

package com.qf.demo2;

public class Person {

    private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Person() {
super();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
} }

获得JSON数据

package com.qf.demo6;

import java.util.ArrayList;

import com.google.gson.Gson;
import com.qf.demo2.Person; public class Test3 { public static void main(String[] args) { ArrayList<Person> list = new ArrayList<>();
list.add(new Person(3, "zhangsan"));
list.add(new Person(5, "lis"));
list.add(new Person(6, "wagw")); Employ employ = new Employ(4, "zhangsan", list); Gson gson = new Gson();
String json = gson.toJson(employ);
System.out.println(json); }
} class Employ{
private int no;
private String name;
private ArrayList<Person> employees;
public Employ(int no, String name, ArrayList<Person> employees) {
super();
this.no = no;
this.name = name;
this.employees = employees;
}
public Employ() {
super();
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Person> getEmployees() {
return employees;
}
public void setEmployees(ArrayList<Person> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Employ [no=" + no + ", name=" + name + ", employees=" + employees + "]";
} }