Как записать json в файл java

Аватар пользователя Сергей Якимович
Сергей Якимович
21 декабря 2022

Для записи json в файл воспользуемся ObjectMapper() :

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class App {
    public static void main(String[] args) throws IOException {
        String fileName = "test.json";
        List<Person> people = new ArrayList<>();
        Person person = new Person("Ivan", 20, Map.of("tel","25-12-86","mail","1@mail.ru"));
        people.add(person);
        person = new Person("Petr", 25, Map.of("tel","35-32-16","mail","2@mail.ru"));
        people.add(person);

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(new File(fileName), people);
    }
}

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class Person {
    String name;
    int age;
    Map<String, String> contacts;

    public Person(String name, int age, Map<String, String> contacts) {
        this.name = name;
        this.age = age;
        this.contacts = contacts;
    }
}

Результат :

[{"name":"Ivan","age":20,"contacts":{"tel":"25-12-86","mail":"1@mail.ru"}},
{"name":"Petr","age":25,"contacts":{"tel":"35-32-16","mail":"2@mail.ru"}}]
1 0

Похожие вопросы