【问题标题】:How to pass JSON input for Map<Person, Person> type to a PUT JAX-RS API?如何将 Map<Person, Person> 类型的 JSON 输入传递给 PUT JAX-RS API?
【发布时间】:2019-02-28 13:48:00
【问题描述】:

我有一个 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。我正在使用 Postman 客户端,当我尝试将 JSON 输入作为键值对传递时,它显示语法错误。为 Person 生成的 JSON 如下所示

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

我需要将此作为键值对作为映射传递。像

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

任何指针我该怎么做?

【问题讨论】:

  • 据我所知,您不能将对象作为键,它们必须是字符串。你可以通过使用序列化的人作为关键来解决这个问题吗?还是重构数据?
  • 使用 Person 的唯一属性作为键?像 id 一样,除非它不像你的例子那样独特?
  • 很遗憾,我无法改变这一点。有没有办法将 JSON 输入传递给这个地图?
  • 我之前没有仔细查看注释,但对于@Consumes,您在列表中有 PLAIN_TEXT。
  • @MichałZiober 我现在不太记得这种情况了,但当时你们的 cmets 确实帮助了我。

标签: java json rest jax-rs


【解决方案1】:

通常,像这样创建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 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&lt;Person, Person&gt; 进行序列化和反序列化:

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 方法用于生成JSON key。正常序列化过程将Person 序列化为JSON 对象。如下第二个文本被打印:

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

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

如您所见,可以选择将JSON 作为Map&lt;Person, Person&gt; 发送,但密钥应该以某种方式表示。您需要查看Person 类的实现。也许您会发现与我的示例有一些相似之处。如果不是,也许它以某种方式配置。首先尝试发送PostMan

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

或者:

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

也许它会起作用。

另见:

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多