gpt4 book ai didi

java - Json反序列化为URL(拦截)

转载 作者:行者123 更新时间:2023-11-30 06:57:20 28 4
gpt4 key购买 nike

我在尝试反序列化 URL

时遇到此错误
Caused by: java.net.MalformedURLException: no protocol: www.boo.com
at java.net.URL.<init>(URL.java:586) ~[na:1.8.0_45]
at java.net.URL.<init>(URL.java:483) ~[na:1.8.0_45]
at java.net.URL.<init>(URL.java:432) ~[na:1.8.0_45]
at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer$Std._deserialize(FromStringDeserializer.java:212) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:122) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:337) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:131) ~[jackson-databind-2.6.2.jar:2.6.2]
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245) ~[jackson-databind-2.6.2.jar:2.6.2]

波乔:

class foo {
...
URL url
...
}

如错误所说,缺少协议(protocol),如果用户未设置协议(protocol),如何在反序列化之前插入协议(protocol)?

最佳答案

我结合了之前的两个答案:

public class Foo {
...
@JsonDeserialize(using = UrlDeseralizer.class)
private URL url;
...
}

public class UrlDeseralizer extends JsonDeserializer<URL> {

private Pattern urlPrefix = Pattern.compile("^(https?://|ftp://).*");

@Override
public URL deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec objectCodec = p.getCodec();
JsonNode node = objectCodec.readTree(p);
String stringUrl = node.asText();
if (!urlPrefix.matcher(stringUrl).matches()) {
return new URL("http://" + stringUrl);
} else {
return new URL(stringUrl);
}
}

}

关于java - Json反序列化为URL(拦截),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523484/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com