如何在 Java 中参数化响应解析? [英] How do I parametrize response parsing in Java?
问题描述
我正在编写一个网络类,并且希望能够解析对不同类的不同响应(仍然存在一对一的关系,但我希望有一个 parseResponse()
处理来自不同端点的所有响应,并且 endpoint.className
具有我应该映射到的预期 classType:
I'm writing a network class and want to be able to parse different responses to different classes (there's still one-to-one relationship but I want to have a single parseResponse()
that will deal with all responses from different endpoints, and endpoint.className
has the expected classType that I should map to):
private Class<?> parseResponse(StringBuilder responseContent, Endpoint endpoint) {
ObjectMapper mapper = new ObjectMapper();
try {
Class<?> object = mapper.readValue(responseContent.toString(), endpoint.className);
// endpoint.className has Class<?> type
if (object instanceof endpoint.className) {
}
} catch (IOException e) {
// handle errors
}
}
但是如果我写 if (object instanceof endpoint.className)
更新:可能更好的选择是将 parse()
方法添加到 Endpoint
类:
Update: probably the better option is to add parse()
method to Endpoint
class:
public Class<?> parseResponse(String responseContent) {
// this.className has Class<?> type (e.g., Foo.class).
}
public enum Endpoint {
FOO (Foo.class),
BAR (Bar.class);
private Class<?> classType;
}
但仍然存在相同的类型错误.
But there're still the same type errors.
推荐答案
您应该将 JSON
反序列化与应用的其他部分分开.您无法为所有响应实现一种方法,但您的响应数量可能有限,您可以为每个类声明一些简单的方法.通常,您只能使用一种带有如下声明的方法:
You should separate JSON
deserialisation from other parts of your app. You can not implement one method for all responses but you probably have a limited number of responses and you can declare some simple methods for each class. Generally, you could have only one method with declaration like below:
public <T> T deserialise(String payload, Class<T> expectedClass) {
Objects.requireNonNull(payload);
Objects.requireNonNull(expectedClass);
try {
return mapper.readValue(payload, expectedClass);
} catch (IOException e) {
throw new IllegalStateException("JSON is not valid!", e);
}
}
现在,您可以反序列化您想要的所有有效负载.您需要提供要接收的 JSON
负载和 POJO
类.
And now, you can deserialise all payloads you want. You need to provide JSON
payload and POJO
class you want to receive back.
显示该概念的简单工作解决方案:
Simple working solution which shows that concept:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.util.Objects;
public class JsonMapper {
private final ObjectMapper mapper = new ObjectMapper();
public JsonMapper() {
// configure mapper instance if required
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
// etc...
}
public String serialise(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not generate JSON!", e);
}
}
public <T> T deserialise(String payload, Class<T> expectedClass) {
Objects.requireNonNull(payload);
Objects.requireNonNull(expectedClass);
try {
return mapper.readValue(payload, expectedClass);
} catch (IOException e) {
throw new IllegalStateException("JSON is not valid!", e);
}
}
public Foo parseResponseFoo(String payload) {
return deserialise(payload, Foo.class);
}
public Bar parseResponseBar(String payload) {
return deserialise(payload, Bar.class);
}
public static void main(String[] args) {
JsonMapper jsonMapper = new JsonMapper();
String bar = "{"bar" : 2}";
System.out.println(jsonMapper.parseResponseBar(bar));
String foo = "{"foo" : 1}";
System.out.println(jsonMapper.parseResponseFoo(foo));
System.out.println("General method:");
System.out.println(jsonMapper.deserialise(foo, Foo.class));
System.out.println(jsonMapper.deserialise(bar, Bar.class));
}
}
class Foo {
public int foo;
@Override
public String toString() {
return "Foo{" +
"foo=" + foo +
'}';
}
}
class Bar {
public int bar;
@Override
public String toString() {
return "Bar{" +
"bar=" + bar +
'}';
}
}
另见:
- 反序列化或序列化任何类型使用 Jackson ObjectMapper 和处理异常的对象
- 什么泛型是具体化的吗?它们是如何解决类型擦除问题的,为什么不进行重大更改就不能添加它们?
- 如何使用 jackson 反序列化为 Kotlin 集合一个>
这篇关于如何在 Java 中参数化响应解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!