我有一个名为“Estudante”的类,我试图用类“Estudante”的对象在json中写一个文件。我的问题是,当我试图将值写入json时,字符串和整型被写入,但数组列表没有写入文件。
下面是代码:
package org.example;
import java.util.ArrayList;
import java.util.Objects;
public class Estudante {
//attributes of the class Estudante
private int nrEstudante;
private String nome;
private int idade;
private ArrayList<String> unidadesCurriculares;
//default constructor (good practice)
public Estudante() {
}
public Estudante(int nrEstudante, String nome, int idade, ArrayList<String>unidadesCurriculares) {
this.nrEstudante = nrEstudante;
this.nome = nome;
this.idade = idade;
this.unidadesCurriculares = unidadesCurriculares;
}
public int getNrEstudante() {
return nrEstudante;
}
public void setNrEstudante(int nrEstudante) {
this.nrEstudante = nrEstudante;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
}
接下来,我创建了主类,尝试在json中创建包含新对象数据的文件
package org.example;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> ucurriculares = new ArrayList<String>();
ucurriculares.add("ingles");
ucurriculares.add("Espanhol");
//ArrayList<Object> unidade = new ArrayList<Object>();
//unidade.add(ucurriculares);
Estudante estudante;
estudante = new Estudante(1234,"Student",16,ucurriculares);
try{
ObjectMapper mapper = new ObjectMapper();
String StrJson = mapper.writeValueAsString(estudante);
mapper.writeValue(new File("estudante.json"),StrJson);
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
这是我的文件的当前输出:
"{\"nrEstudante\":1234,\"nome\":\"Student\",\"idade\":16}"
结果我忘了为数组列表创建setter和getter
1条答案
按热度按时间arknldoa1#
您可以对现有代码尝试以下两种方法中的任何一种:
**方法1:**为www.example.com类的所有属性创建
getters and setters
Estudante.java**方法2:**在
ObjectMapper
上使用mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
。(无需创建getter和setter)**对于方法2:**由于我使用了不同包中的
ObjectMapper
,两种方法的输出都在文件中: