【发布时间】:2016-05-13 00:44:43
【问题描述】:
我编写了一个 REST 服务来从发布请求中提取元数据。我正在使用 spring-data-elasticsearch,并且我制作了一个自定义元数据对象以将 Json 反序列化为如下所示:
@Document(indexName = "metadata_v1", type = "metadata")
public class Metadata {
@Id
private String id;
@Field(type = FieldType.String)
private String uuid;
@Field(type = FieldType.String)
private String userId;
@Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private Date date = null;
@Field(type = FieldType.String)
private String classification;
@Field(type = FieldType.Nested)
private List<NumericKeyValue> numericKeyValue;
@Field(type = FieldType.Nested)
private List<TextKeyValue> textKeyValue;
有一堆 getter 和 setter。
除了numericKeyValue 和textKeyValue Json 数组之外,它适用于所有字段。我无法通过 post 请求发送它们,并意识到我需要编写一个反序列化器。我是为numericKeyValue 做的,据我所知,它应该是这样的:
public class NumericKeyValueJsonDeserializer extends JsonDeserializer<List<NumericKeyValue>>{
@Override
public List<NumericKeyValue> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
TypeReference<List<NumericKeyValue>> typeRef = new TypeReference<List<NumericKeyValue>>(){};
ObjectMapper mapper = new ObjectMapper();
JsonNode root = jp.getCodec().readTree(jp);
String numericKeyValue = root.get("numericKeyValue").asText();
return mapper.readValue( numericKeyValue, typeRef);
}
}
我加了
@JsonDeserialize(using = NumericKeyValueJsonDeserializer.class)
到我的元数据类中的字段声明。
但是,经过大量测试,我意识到 JsonNode root 不仅不包含 "numericKeyValue",而且在我调用 root.asText() 时给了我一个完全空的字符串。
我一直在使用 Postman 向我的端点发送一个 post 请求
@RequestMapping(value="/metadata_v1/ingest", method=RequestMethod.POST, consumes="application/json")
public @ResponseBody Metadata createEntry(@RequestBody Metadata entry){
repository.save(entry);
return entry;
}
包含以下Json:
{
"numericKeyValue":
[
{
"key": "velocity",
"value": 55.5
},
{
"key": "angle",
"value": 90
}
]
}
我的映射如下所示:
"numericKeyValue" : {
"type" : "nested",
"properties" : {
"key" : {"type" : "string"},
"value" : {"type" : "double"}
}
}
如果需要,我可以展示更多内容。我想如果我能以某种方式获取我在 Java 中发送的 JSON,我会很好,也许是一个字符串。我得到了导致空指针异常的空字符串,当我尝试String numericKeyValue = jp.getText() 时,字符串只是“[”的当前标记,我猜它至少不是空字符串,但仍然没有帮助我。
非常感谢任何帮助或建议。
【问题讨论】:
标签: java json spring rest post