java的参数中feature_如何参数化Java中的响应解析?

论坛 期权论坛 期权     
选择匿名的用户   2021-6-2 19:20   8855   0

小编典典

您应该将JSON反序列化与应用程序的其他部分分开。您不能为所有响应实现一种方法,但是响应数量可能有限,并且可以为每个类声明一些简单方法。通常,您只能使用一种具有如下声明的方法:

public T deserialise(String payload, Class 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类。

显示该概念的简单工作解决方案:

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 deserialise(String payload, Class 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 +

'}';

}

}

2020-09-23

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP