[英]How to deserialize a custom object that has a parameter string with escaped JSON and dynamic key into Java Object
I have a JSON as below我有一个 JSON 如下
{
"fixedKey1" : "value1",
"fixedKey2" : "value2",
"fixedKey3" : "{\"DYNAMICKEY\":{\"innerKey1\":\"innerVal1\",\"innerKey2\":\"innerVal1\"}}"
}
I'm interested to extract only the inner JSON key and values in the fixedKey3.我有兴趣只提取内部 JSON 键和 fixedKey3 中的值。
Notice that fixedKey3 is a complex string that has a dynamic key that I cannot control.请注意,fixedKey3 是一个复杂的字符串,它有一个我无法控制的动态键。 It is different in each response so that can never be a fixed key parameter.
每个响应都不同,因此永远不能是固定的关键参数。
So far I've written the below code, doing trial and error with no success到目前为止,我已经编写了以下代码,反复试验但没有成功
Below is the outer class of the entire JSON下面是整个JSON的外层class
class Outer {
String fixedKey1;
String fixedKey2;
@JsonProperty("fixedKey3")
public void setFixedKey3(String input) {
ObjectMapper mapper = new ObjectMapper();
//NEED help here
mapper.readValue(input, InnerData.class);
}
}
Below is the inner class which is supposed to contain inner values data.下面是内部 class 应该包含内部值数据。
class InnerData {
String innerKey1;
String innerKey2;
}
I'll be very grateful if you can help me.如果您能帮助我,我将不胜感激。 Thanks in advance.
提前致谢。
The first problem about your scenario is about the "fixedKey3": "{\"DYNAMICKEY\":{\"innerKey1\":\"innerVal1\",\"innerKey2\":\"innerVal1\"}}"
containing escaped double quotes: a first step to solve your question is using the readTree
method and read the JsonNode
obtained with asText
to get rid of the escaped double quotes like below:关于您的场景的第一个问题是关于
"fixedKey3": "{\"DYNAMICKEY\":{\"innerKey1\":\"innerVal1\",\"innerKey2\":\"innerVal1\"}}"
包含转义双引号:解决您的问题的第一步是使用readTree
方法并读取使用JsonNode
获得的asText
以摆脱转义的双引号,如下所示:
JsonNode root = mapper.readTree(json);
//s will contains {"DYNAMICKEY":{"innerKey1":"innerVal1","innerKey2":"innerVal1"}}
String s = root.get("fixedKey3").asText();
To obtain the "DYNAMICKEY"
dynamic key you can use the fieldNames
method and with the treeToValue
method mapping the obtained JsonNode
to one InnerData
object as you expect:要获得
"DYNAMICKEY"
动态键,您可以使用fieldNames
方法并使用treeToValue
方法将获得的JsonNode
映射到一个InnerData
object,如您所料:
JsonNode dinamycKeyNode = mapper.readTree(s);
String dynamicKey = dinamycKeyNode.fieldNames().next(); //<-- it will contains your dynamic key
//mapping the {"innerKey1":"innerVal1","innerKey2":"innerVal1"} to InnerData
InnerData innerData = mapper.treeToValue(dinamycKeyNode.get(dynamicKey), InnerData.class);
Note: for semplicity in the InnerData
class the fields innerKey1
and innerKey2
are public.注意:为了简单起见,
InnerData
class 字段innerKey1
和innerKey2
是公共的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.