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



我有一个PUT类型的JAX-RS REST端点,我应该将Map传递给这个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 类生成了 JSON,但我无法将其作为 JSON 输入传递给此 API。我正在使用邮递员客户端,当我尝试将 JSON 输入作为键值对传递时,它说语法错误。为 Person 生成的 JSON 如下所示

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

我需要将其作为键值对作为映射传递。类似的东西

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

任何指示我该怎么做?

一般来说,创建这样的Map看起来是个坏主意。JSON Object可以转换为JavaMap,其中keyStringvalue是任何Object:可以是另一种MaparrayPOJO或简单类型。因此,通常您的JSON应如下所示:

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

别无选择。如果你想在Java映射POJO->POJO你需要指示反序列化器如何将JSON-String-key转换为对象。没有其他选择。我将尝试使用Jackson库来解释此过程,因为它在RESTful Web Services中使用最多。让我们定义Person适合您的JSON有效负载的类。

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方法。除了构造函数和toString方法public Person(String value)其他一切看起来都很正常。现在,让我们看一下这个构造函数和toString方法。它们是相关的:toStringPerson实例构建String,构造函数从String构建Person。我们可以将第一次转换称为序列化,第二次转换称为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。也许你会发现与我的例子有一些相似之处。如果没有,也许它以某种方式配置了。首先尝试发送PostMan

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

或:

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

也许它会起作用。

另请参阅:

  • 使用杰克逊映射序列化和反序列化
  • 带有 Jersey 2.2
  • 和 Jackson 2.1 的自定义对象映射器
  • JBoss resteasy - 定制杰克逊供应商

最新更新