jackson 正在尝试使用带有数组列表的对象写入json文件

b5lpy0ml  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(152)

我有一个名为“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

arknldoa

arknldoa1#

您可以对现有代码尝试以下两种方法中的任何一种:
**方法1:**为www.example.com类的所有属性创建getters and settersEstudante.java
**方法2:**在ObjectMapper上使用mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);(无需创建getter和setter)
**对于方法2:**由于我使用了不同包中的ObjectMapper

import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
  • 需要在pom.xml中添加此依赖项 *
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.4</version>
        </dependency>

两种方法的输出都在文件中:

"{\"nrEstudante\":1234,\"nome\":\"Student\",\"idade\":16,\"unidadesCurriculares\":[\"ingles\",\"Espanhol\"]}"

相关问题