-4

I have the following class:

public class Person {
    private String id;
    private String first_name;
    private String last_name;

    Person(String id, String first_name, String last_name) {
        this.id = id;
        this.last_name = last_name;
        this.first_name = first_name;
    }
}

I want to be able to have a file that has JSON format so:

[
   {
      "id":"1",
      "first_name":"bob",
      "last_name":"marley"
   },
   {
      "id":"2",
      "first_name":"bob",
      "last_name":"ross"
   }
]

The file is a list of all Person objects. So I'm trying to create two methods:

  1. Method that converts List<Person> into a JSON file like above.
  2. Method that reads the JSON file into a List<Person>.

What would be the best way (most elegant way) to implement this in Java 8? Do I need to add some methods to Person class? Or is there another way?

Since it's a List of objects that contain only Strings, is there something elegant for that?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • 1
    Regarding [this post](https://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java-me) there are many possibilities to the conversion. There is also a nice [comparison between some tools](https://www.overops.com/blog/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/). – flaxel Apr 03 '21 at 14:28
  • @flaxel Thanks, I'll check it out. For all the others - why the downvotes? Please explain so I can approve the question – vesii Apr 03 '21 at 14:52
  • 1
    I think because the question is too non-specific. It would help if you limit yourself to one tool. Additionally, it would be important if you try it yourself once and then ask if you have a bug in the implementation. – flaxel Apr 03 '21 at 14:54
  • I downvoted you because you just dumped your task and didn't include any effort to solve it yourself. – Robert Apr 03 '21 at 19:46

1 Answers1

2

there are multiple different libraries that you could use for this, but heres a simple example using jackson:

public static void main(String[] args) throws IOException {
    Path path = Path.of("people.json");
    ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
            .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
            .registerModule(new ParanamerModule());
    List<Person> people = List.of(new Person("3213914912", "SomeFirstName", "SomeSecondName"));

    write(path, mapper, people);
    read(path, mapper).forEach(System.out::println);
}

private static void write(Path path, ObjectMapper mapper, List<Person> people) throws IOException {
    mapper.writeValue(path.toFile(), people);
}

private static List<Person> read(Path path, ObjectMapper mapper) throws IOException {
    return mapper.readValue(path.toFile(), TypeFactory.defaultInstance()
            .constructCollectionType(List.class, Person.class));
}
Suic
  • 433
  • 1
  • 3
  • 9