![](/img/trans.png)
[英]Simplest way to decode and deserialize field whose value is a base64 encoded, stringified JSON blob with Jackson
[英]Decode base64 encoded JSON to POJO with jackson and spring-boot
我有這樣的要求
{
"varA" : "A",
"varB" : "TCFNhbiBKb3NlMRgwFgYDVQQK"
}
其中關鍵字varB
是base64編碼的JSON字符串。 像這樣的東西:
{
"nestedVarB1": "some value here",
"nestedVarB2" : "some other value here"
}
我想將其轉換成這樣的一些POJO:
@Data
public class MyRequest {
private String varA;
private B varB;
}
@Data
public class B {
private String nestedVarB1;
private String nestedVarB2;
}
我通過像堆棧溢出的幾種解決方案,去這個和這個 ,但我想的JSON直接轉換為類型的對象MyRequest
也許寫某種傑克遜解串器。
如何使用Jackson和Spring Boot將JSON直接轉換為MyRequest
?
注意:
MyRequest
和B
非常大,並且B
可以進一步嵌套,因此手動執行將是一項艱巨的任務。 我已經做了一些實驗,這是一個簡單的Jackson Deserializer,應該可以為您工作。
Deserializer實現ContextualDeserializer接口,以訪問實際的bean屬性(例如varB
)。 這是檢測正確結果類型的必要條件,因為解串器本身可以附加到任何類型的字段。
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import java.io.IOException;
import java.util.Base64;
public class Base64Deserializer extends JsonDeserializer<Object> implements ContextualDeserializer {
private Class<?> resultClass;
@Override
public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
this.resultClass = property.getType().getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
String value = parser.getValueAsString();
Base64.Decoder decoder = Base64.getDecoder();
try {
ObjectMapper objectMapper = new ObjectMapper();
byte[] decodedValue = decoder.decode(value);
return objectMapper.readValue(decodedValue, this.resultClass);
} catch (IllegalArgumentException | JsonParseException e) {
String fieldName = parser.getParsingContext().getCurrentName();
Class<?> wrapperClass = parser.getParsingContext().getCurrentValue().getClass();
throw new InvalidFormatException(
parser,
String.format("Value for '%s' is not a base64 encoded JSON", fieldName),
value,
wrapperClass
);
}
}
}
這是一個映射類的例子。
public class MyRequest {
private String varA;
@JsonDeserialize(using = Base64Deserializer.class)
private B varB;
public String getVarA() {
return varA;
}
public void setVarA(String varA) {
this.varA = varA;
}
public B getVarB() {
return varB;
}
public void setVarB(B varB) {
this.varB = varB;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.