如何将 Map<Person, Person> 类型的 JSON 输入传递给 PUT JAX-RS API?

How to pass JSON input for Map<Person, Person> type to a PUT JAX-RS API?

我有一个 PUT 类型的 JAX-RS REST 端点,我应该将一个映射传递给这个 API。

@PUT
@Path("/some/path")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML,
        MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response updatePerson(HashMap<Person, Person> map) {

//some code here
}

我为 Person class 生成了 JSON,但我无法将其作为 JSON 输入传递给此 API。我正在使用 Postman 客户端,当我尝试将 JSON 输入作为键值对传递时,它显示语法错误。 JSON 为 Person 生成的内容如下所示

  {"name":"abc","weight":100.0,"id":"123"}

我需要将其作为键值对作为地图传递。像

 {
   {"name":"abc","weight":100.0,"id":"123"} : 
   {"name":"def","weight":200.0,"id":"123"}
 }

任何指示我该怎么做?

通常,像这样创建 Map 似乎不是个好主意。 JSON Object 可以转换为 Java Map 其中 keyStringvalue 是任何 Object: 可以是另一个 MaparrayPOJO 或简单类型。所以,通常你的 JSON 应该是这样的:

{
    "key" : { .. complex nested object .. }
}

别无选择。如果你想在 Java 映射 POJO -> POJO 中,你需要指示解串器如何将 JSON-String-key 转换为一个东西。没有其他选择。我将尝试使用 Jackson 库来解释这个过程,因为它在 RESTful Web Services 中最常用。让我们定义适合您的 JSON 有效负载的 Person class。

class Person {

    private String name;
    private double weight;
    private int id;

    public Person() {
    }

    public Person(String value) {
        String[] values = value.split(",");
        name = values[0];
        weight = Double.valueOf(values[1]);
        id = Integer.valueOf(values[2]);
    }

    public Person(String name, double weight, int id) {
        this.name = name;
        this.weight = weight;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return name + "," + weight + "," + id;
    }
}

因为它在Map中用作键我们需要实现hashCodeequals方法。除了 public Person(String value) 构造函数和 toString 方法,其他一切看起来都很正常。现在,让我们看一下这个构造函数和 toString 方法。它们是相互关联的:toStringPerson 实例构建 String,构造函数从 String 构建 Person。我们可以将第一个转换称为 serialisation,将第二个转换称为 deserialisation Map 序列化和反序列化中的密钥。 (这两个实现的好不好,这是另外一回事了,我只是想展示一下背后的想法,在生产之前应该改进一下)

让我们使用这些知识和 Jackson 特征来序列化和反序列化 Map<Person, Person>:

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.MapType;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        // register deserializer for Person as keys.
        SimpleModule module = new SimpleModule();
        module.addKeyDeserializer(Person.class, new PersonKeyDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Create example Map
        Person key = new Person("Rick", 80.5, 1);
        Person value = new Person("Morty", 40.1, 2);
        Map<Person, Person> personMap = new HashMap<>();
        personMap.put(key, value);

        // Serialise Map to JSON
        String json = mapper.writeValueAsString(personMap);
        System.out.println(json);

        // Deserialise it back to `Object`
        MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, Person.class, Person.class);
        System.out.println(mapper.readValue(json, mapType).toString());
    }
}

class PersonKeyDeserializer extends KeyDeserializer {

    @Override
    public Object deserializeKey(String key, DeserializationContext ctxt) {
        return new Person(key);
    }
}

以上代码首先打印 JSON:

{
  "Rick,80.5,1" : {
    "name" : "Morty",
    "weight" : 40.1,
    "id" : 2
  }
}

如你所见,PersontoString方法被用来生成JSONkey。正常序列化过程将 Person 序列化为 JSON 对象。下面第二个文本被打印:

{Rick,80.5,1=Morty,40.1,2}

这是 Map 及其键和值的默认表示。因为两者都是 Person 对象,所以调用了 toString 方法。

如您所见,有一个选项可以将 JSON 发送为 Map<Person, Person>,但密钥应该以某种方式表示。您需要查看 Person class 实现。也许您会发现与我的示例有一些相似之处。如果不是,则可能是以某种方式配置的。首先尝试发送 PostMan:

{
   "123" : {"name":"def","weight":200.0,"id":"123"}
}

或者:

{
   "{\"name\":\"abc\",\"weight\":100.0,\"id\":\"123\"}":{
      "name":"def",
      "weight":200.0,
      "id":"123"
   }
}

也许会奏效。

另请参阅: