通常,像这样创建Map 看起来是个坏主意。 JSON Object 可以转换为Java Map 其中key 是String 和value 是任何Object:可以是另一个Map、array、POJO 或简单类型。所以,通常你的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 中用作键,所以我们需要实现hashCode 和equals 方法。除了public Person(String value) 构造函数和toString 方法,其他一切看起来都很正常。现在,让我们看看这个构造函数和toString 方法。它们是相关的:toString 从Person 实例构建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
}
}
如您所见,Person 的toString 方法用于生成JSON key。正常序列化过程将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"
}
}
也许它会起作用。
另见: