< Java JSON

Java JSON - Moshi

Szerző: Sallai András

Copyright © 2025, Sallai András

Szerkesztve: 2025

Licenc: CC BY-SA 4.0

Web: https://szit.hu

Bevezetés

A Moshi egy Java programozói könyvtár JSON tartalmak kezelésére.

https://github.com/square/moshi

Beszerzés

Maven

<dependency> <groupId>com.squareup.moshi</groupId> <artifactId>moshi</artifactId> <version>1.15.2</version> </dependency>

Employee osztály

package com.example; public class Employee { private int id; private String name; private String city; private double salary; private String birth; public Employee() {} public Employee(int id, String name, String city, double salary, String birth) { this.id = id; this.name = name; this.city = city; this.salary = salary; this.birth = birth; } public Employee(String name, String city, double salary, String birth) { this.name = name; this.city = city; this.salary = salary; this.birth = birth; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } }

module-info.java

Ha van module-info.java fájl:

module com.example { requires javafx.controls; requires javafx.fxml; requires transitive javafx.graphics; requires com.squareup.moshi; opens com.example to javafx.fxml, com.squareup.moshi; exports com.example; }

ArrayList-ből JSON string

import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; //... Employee[] employeeArray = employeeList.toArray(new Employee[employeeList.size()]); Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Employee[]> jsonAdapter = moshi.adapter(Employee[].class).indent(" "); String json = jsonAdapter.toJson(employeeArray);

JSON string-ből ArrayList

Employee[] employees2 = jsonAdapter.fromJson(json); ArrayList<Employee> employeeList = new ArrayList<>(Arrays.asList(employees2)); System.out.println(employeeList.get(0).getName());

LocalDate használata

package com.example; import com.squareup.moshi.FromJson; import com.squareup.moshi.ToJson; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class LocalDateJsonAdapter { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; @ToJson String toJson(LocalDate date) { return date.format(FORMATTER); } @FromJson LocalDate fromJson(String date) { return LocalDate.parse(date, FORMATTER); } }

Használat:

Moshi moshi = new Moshi.Builder() .add(new LocalDateJsonAdapter()) .build(); JsonAdapter<Employee[]> jsonAdapter = moshi.adapter(Employee[].class).indent(" ");