[英]Convert java object in JSON
我正在尝试在JSON中转换一个简单的Java对象。 我正在使用Google Gson库,它可以工作,但是我想要这种形式的完整JSON对象:
{"Studente":[{ "nome":"John", "cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
这是我的课:
public class Studente {
private String nome;
private String cognome;
private String matricola;
private String dataNascita;
public Studente(){
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getDataNascita() {
return dataNascita;
}
public void setDataNascita(String dataNascita) {
this.dataNascita = dataNascita;
}
}
这是测试人员:
Studente x = new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson = new Gson();
String toJson = gson.toJson(x, Studente.class);
System.out.println("ToJSON "+toJson);
我在toJson中遇到了这个问题: {"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}
您要实现的Json不是单个Studente对象的表示,而是包含一个Studente对象列表的对象的表示,该对象具有单个条目。
因此,您将需要创建一个包含Studente对象列表的额外对象,将一个实例添加到列表中,然后序列化包含该列表的对象。
不过,有一个小问题。 本质上,您是在要求包装对象的列表具有以大写字母开头的属性名称。 可以这样做,但是破坏了Java编码约定。
最好为学生列表编写一个包装器。 像这样:
import java.util.ArrayList;
public class StudentWrapper {
private ArrayList<Studente> studente;
public StudentWrapper() {
studente = new ArrayList<Studente>();
}
public void addStudent(Studente s){
studente.add(s);
}
}
转换为JSON的代码:
Studente x=new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson=new Gson();
StudentWrapper studentWrapper = new StudentWrapper();
studentWrapper.addStudent(x);
String toJson=gson.toJson(studentWrapper, StudentWrapper.class);
System.out.println("ToJSON "+toJson);
输出将是这样。 您想要的方式。
ToJSON {"studente":[{"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.