【问题标题】:Is there a way in Jackson to write HashMap in to a list of object and vice versa杰克逊有没有办法将 HashMap 写入对象列表,反之亦然
【发布时间】:2018-01-12 14:13:01
【问题描述】:

我想变身

 HashMap<String, Car> to JSON list of cars

序列化时和从

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

反序列化时。

我知道我可以编写一个自定义序列化器/反序列化器,但我想知道在 jackson 中是否有更简单/内置的方法来实现这一点。

【问题讨论】:

  • 不是序列化整个地图,而是仅序列化您通过调用values() 方法获得的值的集合。
  • 所以你是说创建一个密封器然后只做 map.values() ?
  • 这应该会为你提供一个 json 的汽车列表。
  • 这种方法的唯一问题是我在程序中创建的每个映射都将使用该序列化程序,因此如果我有 Map 它会使用 values() 进行序列化...所以我猜我说什么我只能限制 Map 序列化
  • 我认为您需要提供一些实际代码。你说的没有多大意义。

标签: java json serialization jackson


【解决方案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'}}}    

【讨论】:

  • 这适用于从地图到列表,但反过来呢?反序列化列表 以映射?
  • 我想我只是为了创建一个 setCars() 方法并接受 Collection 并转换为地图
猜你喜欢
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
相关资源
最近更新 更多