杰克逊是否有办法将HashMap写入对象列表,反之亦然

时间:2018-01-12 14:13:02

标签: java json serialization jackson

我想转型

 HashMap<String, Car> to JSON list of cars

序列化时和

 List<Car> (JSON) to HashMap<String, Car> 

反序列化时。

我知道我可以编写自定义序列化器/解串器,但我想知道杰克逊是否有更容易/内置的方法来实现这一点。

1 个答案:

答案 0 :(得分:1)

假设你的HashMap的键也在你的值对象中(就像汽车的VIN一样),所以你可以在以后轻松地重新构建密钥,然后注释@JsonGetter / @JsonSetter可以提供帮助:

让我们说你有类似汽车租赁站的东西:

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CarRentalStation {

    private String location = "Atlanta";
    private Map<String, Car> cars = new HashMap<String, Car> (){{
        put("A123", new Car("A123", "BMW 120d"));
        put("B321", new Car("B321", "Volkswagen Golf 2.0 TDI"));
    }};

    public String getLocation() {
        return location;
    }

    @JsonGetter("cars")
    public List<Car> getCarsAsList() {
        return cars.values().stream().collect(Collectors.<Car>toList());
    }

    @JsonSetter("cars")
    public void setCarsAsList(List<Car> cars) {
        Map<String, Car> deserializedCars = cars.stream().collect(Collectors.toMap(Car::getVin, car -> car));
        this.cars = deserializedCars;
    }

    //toString ...    
}

汽车看起来像那样:

public class Car {

    private String vin;
    private String model;

    Car() {
    }

    public Car(String vin, String model) {
        this.vin = vin;
        this.model = model;
    }

    public String getVin() {
        return vin;
    }

    public String getModel() {
        return model;
    }   

    // toString ... 
}

您可以轻松地序列化/反序列化它:

ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(new CarRentalStation());
System.out.println(json);
// prints: {"location":"Atlanta","cars":[{"vin":"B321","model":"Volkswagen Golf 2.0 TDI"},{"vin":"A123","model":"BMW 120d"}]}

CarRentalStation deserializedCarRentalStation =  om.readValue(json, CarRentalStation.class);
System.out.println(deserializedCarRentalStation.toString());
// prints: CarRentalStation{location='Atlanta', cars={B321=Car{vin='B321', model='Volkswagen Golf 2.0 TDI'}, A123=Car{vin='A123', model='BMW 120d'}}}