簡體   English   中英

轉換JSON中的Java對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM