当kotlin在每个块中更改其类型时,如何从json响应中解析answerData键?我试图保留它,但无法键入cast。如何解析应答数据?
{
"status": "OK",
"data": [
{
"id": 10,
"answerData": null
},
{
"id": 21,
"answerData": {
"selectionOptionId": 0,
"selectionOptionText": null
}
},
{
"id": 45,
"answerData": {
"IsAffiliatedWithSeller": false,
"AffiliationDescription": null
}
},
{
"id" : 131,
"answerData" : [
{ "2" : "Chapter 11" },
{ "3" : "Chapter 12" },
{ "1" : "Chapter 7" }
]
},
{
"id" : 140,
"answerData" : [
{
"liabilityTypeId" : 2,
"monthlyPayment" : 200,
"remainingMonth" : 2,
"liabilityName" : "Separate Maintenance",
"name" : "Two"
},
{
"liabilityTypeId" : 1,
"monthlyPayment" : 300,
"remainingMonth" : 1,
"liabilityName" : "Child Support",
"name" : "Three"
}
]
}
]
}
Json响应错误。不需要在客户端处理此响应,Json响应应该从服务器端更改。否则,这将是你未来的一个巨大负担。Json对象应具有正确定义的键及其值。
输入JSON的设计很糟糕,真的很难使用。让我说:
答案数据
属性的元素和集合与数十个缺点混合在一起;当然,任何都不适合您,因为Gson甚至不知道这些有效负载应该反序列化为什么。
由于您没有提供映射,我将提供一个示例,演示如何反序列化如此糟糕的JSON文档。这还包括:
为了解决第一个问题,元素与数组/列表,我在S. O.找到了一个即用型解决方案:
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class AlwaysListTypeAdapterFactory<E> implements TypeAdapterFactory {
@Nullable
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
if (!List.class.isAssignableFrom(typeToken.getRawType())) {
return null;
}
final Type elementType = resolveTypeArgument(typeToken.getType());
@SuppressWarnings("unchecked")
final TypeAdapter<E> elementTypeAdapter = (TypeAdapter<E>) gson.getAdapter(TypeToken.get(elementType));
@SuppressWarnings("unchecked")
final TypeAdapter<T> alwaysListTypeAdapter = (TypeAdapter<T>) new AlwaysListTypeAdapter<>(elementTypeAdapter).nullSafe();
return alwaysListTypeAdapter;
}
private static Type resolveTypeArgument(final Type type) {
if (!(type instanceof ParameterizedType)) {
return Object.class;
}
final ParameterizedType parameterizedType = (ParameterizedType) type;
return parameterizedType.getActualTypeArguments()[0];
}
private static final class AlwaysListTypeAdapter<E> extends TypeAdapter<List<E>> {
private final TypeAdapter<E> elementTypeAdapter;
private AlwaysListTypeAdapter(final TypeAdapter<E> elementTypeAdapter) {
this.elementTypeAdapter = elementTypeAdapter;
}
@Override
public void write(final JsonWriter out, final List<E> list) {
throw new UnsupportedOperationException();
}
@Override
public List<E> read(final JsonReader in) throws IOException {
final List<E> list = new ArrayList<>();
final JsonToken token = in.peek();
switch ( token ) {
case BEGIN_ARRAY:
in.beginArray();
while ( in.hasNext() ) {
list.add(elementTypeAdapter.read(in));
}
in.endArray();
break;
case BEGIN_OBJECT:
case STRING:
case NUMBER:
case BOOLEAN:
list.add(elementTypeAdapter.read(in));
break;
case NULL:
throw new AssertionError("Must never happen: check if the type adapter configured with .nullSafe()");
case NAME:
case END_ARRAY:
case END_OBJECT:
case END_DOCUMENT:
throw new MalformedJsonException("Unexpected token: " + token);
default:
throw new AssertionError("Must never happen: " + token);
}
return list;
}
}
}
接下来,对于第2项,可以实现如下推断类型适配器工厂:
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class DeducingTypeAdapterFactory<V> implements TypeAdapterFactory {
public interface TypeAdapterProvider {
@Nonnull
<T> TypeAdapter<T> provide(@Nonnull TypeToken<T> typeToken);
}
private final Predicate<? super TypeToken<?>> isSupported;
private final BiFunction<? super JsonElement, ? super TypeAdapterProvider, ? extends V> deduce;
public static <V> TypeAdapterFactory create(final Predicate<? super TypeToken<?>> isSupported,
final BiFunction<? super JsonElement, ? super TypeAdapterProvider, ? extends V> deduce) {
return new DeducingTypeAdapterFactory<>(isSupported, deduce);
}
@Override
@Nullable
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
if (!isSupported.test(typeToken)) {
return null;
}
final Map<TypeToken<?>, TypeAdapter<?>> cache = new ConcurrentHashMap<>();
final TypeAdapter<V> deducedTypeAdapter = new TypeAdapter<V>() {
@Override
public void write(final JsonWriter jsonWriter, final V value) {
throw new UnsupportedOperationException();
}
@Override
public V read(final JsonReader jsonReader) {
final JsonElement jsonElement = Streams.parse(jsonReader);
return deduce.apply(jsonElement, new TypeAdapterProvider() {
@Nonnull
@Override
public <TT> TypeAdapter<TT> provide(@Nonnull final TypeToken<TT> typeToken) {
final TypeAdapter<?> cachedTypeAdapter = cache.computeIfAbsent(typeToken, tt -> gson.getDelegateAdapter(DeducingTypeAdapterFactory.this, tt));
@SuppressWarnings("unchecked")
final TypeAdapter<TT> typeAdapter = (TypeAdapter<TT>) cachedTypeAdapter;
return typeAdapter;
}
});
}
}
.nullSafe();
@SuppressWarnings("unchecked")
final TypeAdapter<T> typeAdapter = (TypeAdapter<T>) deducedTypeAdapter;
return typeAdapter;
}
}
基本上,它本身不进行推断,只使用策略设计模式将筛选和推断作业委托给其他地方。
现在,让我们假设您的映射足够“通用”(包括使用JsonAdapter来强制单个元素成为列表):
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode
@ToString
final class Response<T> {
@Nullable
@SerializedName("status")
private final String status;
@Nullable
@SerializedName("data")
private final T data;
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode
@ToString
final class Answer {
@SerializedName("id")
private final int id;
@Nullable
@SerializedName("answerData")
@JsonAdapter(AlwaysListTypeAdapterFactory.class)
private final List<AnswerDatum> answerData;
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
abstract class AnswerDatum {
interface Visitor<R> {
R visit(@Nonnull Type1 answerDatum);
R visit(@Nonnull Type2 answerDatum);
R visit(@Nonnull Type3 answerDatum);
R visit(@Nonnull Type4 answerDatum);
}
abstract <R> R accept(@Nonnull Visitor<? extends R> visitor);
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
static final class Type1 extends AnswerDatum {
@SerializedName("selectionOptionId")
private final int selectionOptionId;
@Nullable
@SerializedName("selectionOptionText")
private final String selectionOptionText;
@Override
<R> R accept(@Nonnull final Visitor<? extends R> visitor) {
return visitor.visit(this);
}
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
static final class Type2 extends AnswerDatum {
@SerializedName("IsAffiliatedWithSeller")
private final boolean isAffiliatedWithSeller;
@Nullable
@SerializedName("AffiliationDescription")
private final String affiliationDescription;
@Override
<R> R accept(@Nonnull final Visitor<? extends R> visitor) {
return visitor.visit(this);
}
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
static final class Type3 extends AnswerDatum {
@Nonnull
private final String key;
@Nullable
private final String value;
@Override
<R> R accept(@Nonnull final Visitor<? extends R> visitor) {
return visitor.visit(this);
}
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, staticName = "of")
@Getter
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
static final class Type4 extends AnswerDatum {
@SerializedName("liabilityTypeId")
private final int liabilityTypeId;
@SerializedName("monthlyPayment")
private final int monthlyPayment;
@SerializedName("remainingMonth")
private final int remainingMonth;
@Nullable
@SerializedName("liabilityName")
private final String liabilityName;
@Nullable
@SerializedName("name")
private final String name;
@Override
<R> R accept(@Nonnull final Visitor<? extends R> visitor) {
return visitor.visit(this);
}
}
}
请注意AnswerDatum如何使用Visitor设计模式来避免显式类型转换。我不确定在Java中使用密封类时如何利用它。
public final class DeducingTypeAdapterFactoryTest {
private static final Pattern digitsPattern = Pattern.compile("^\\d+$");
private static final TypeToken<String> stringTypeToken = new TypeToken<>() {};
private static final TypeToken<AnswerDatum.Type1> answerDatumType1TypeToken = new TypeToken<>() {};
private static final TypeToken<AnswerDatum.Type2> answerDatumType2TypeToken = new TypeToken<>() {};
private static final TypeToken<AnswerDatum.Type4> answerDatumType4TypeToken = new TypeToken<>() {};
private static final Gson gson = new GsonBuilder()
.disableInnerClassSerialization()
.disableHtmlEscaping()
.registerTypeAdapterFactory(DeducingTypeAdapterFactory.create(
typeToken -> AnswerDatum.class.isAssignableFrom(typeToken.getRawType()),
(jsonElement, getTypeAdapter) -> {
if ( jsonElement.isJsonObject() ) {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
// type-1? hopefully...
if ( jsonObject.has("selectionOptionId") ) {
return getTypeAdapter.provide(answerDatumType1TypeToken)
.fromJsonTree(jsonElement);
}
// type-2? hopefully...
if ( jsonObject.has("IsAffiliatedWithSeller") ) {
return getTypeAdapter.provide(answerDatumType2TypeToken)
.fromJsonTree(jsonElement);
}
// type-3? hopefully...
if ( jsonObject.size() == 1 ) {
final Map.Entry<String, JsonElement> onlyEntry = jsonObject.entrySet().iterator().next();
final String key = onlyEntry.getKey();
if ( digitsPattern.matcher(key).matches() ) {
final String value = getTypeAdapter.provide(stringTypeToken)
.fromJsonTree(onlyEntry.getValue());
return AnswerDatum.Type3.of(key, value);
}
}
// type-4? hopefully...
if ( jsonObject.has("liabilityTypeId") ) {
return getTypeAdapter.provide(answerDatumType4TypeToken)
.fromJsonTree(jsonElement);
}
}
throw new UnsupportedOperationException("can't parse: " + jsonElement);
}
))
.create();
private static final TypeToken<Response<List<Answer>>> listOfAnswerResponseType = new TypeToken<>() {};
@Test
public void testEqualsAndHashCode() throws IOException {
final Object expected = Response.of(
"OK",
List.of(
Answer.of(
10,
null
),
Answer.of(
21,
List.of(
AnswerDatum.Type1.of(0, null)
)
),
Answer.of(
45,
List.of(
AnswerDatum.Type2.of(false, null)
)
),
Answer.of(
131,
List.of(
AnswerDatum.Type3.of("2", "Chapter 11"),
AnswerDatum.Type3.of("3", "Chapter 12"),
AnswerDatum.Type3.of("1", "Chapter 7")
)
),
Answer.of(
140,
List.of(
AnswerDatum.Type4.of(2, 200, 2, "Separate Maintenance", "Two"),
AnswerDatum.Type4.of(1, 300, 1, "Child Support", "Three")
)
)
)
);
try (final JsonReader jsonReader = openJsonInput()) {
final Object actual = gson.fromJson(jsonReader, listOfAnswerResponseType.getType());
Assertions.assertEquals(expected, actual);
}
}
@Test
public void testVisitor() throws IOException {
final Object expected = List.of(
"21:0",
"45:false",
"131:2:Chapter 11",
"131:3:Chapter 12",
"131:1:Chapter 7",
"140:Two",
"140:Three"
);
try (final JsonReader jsonReader = openJsonInput()) {
final Response<List<Answer>> response = gson.fromJson(jsonReader, listOfAnswerResponseType.getType());
final List<Answer> data = response.getData();
assert data != null;
final Object actual = data.stream()
.flatMap(answer -> Optional.ofNullable(answer.getAnswerData())
.map(answerData -> answerData.stream()
.map(answerDatum -> answerDatum.accept(new AnswerDatum.Visitor<String>() {
@Override
public String visit(@Nonnull final AnswerDatum.Type1 answerDatum) {
return answer.getId() + ":" + answerDatum.getSelectionOptionId();
}
@Override
public String visit(@Nonnull final AnswerDatum.Type2 answerDatum) {
return answer.getId() + ":" + answerDatum.isAffiliatedWithSeller();
}
@Override
public String visit(@Nonnull final AnswerDatum.Type3 answerDatum) {
return answer.getId() + ":" + answerDatum.getKey() + ':' + answerDatum.getValue();
}
@Override
public String visit(@Nonnull final AnswerDatum.Type4 answerDatum) {
return answer.getId() + ":" + answerDatum.getName();
}
})
)
)
.orElse(Stream.empty())
)
.collect(Collectors.toUnmodifiableList());
Assertions.assertEquals(expected, actual);
}
}
private static JsonReader openJsonInput() throws IOException {
return // ... your code code here ...
}
}
那就是了。
我发现这非常困难和不必要的复杂。请要求您的服务器端伙伴永远修复他们的设计(请注意当前情况如何使反序列化比设计良好时更难)。
正如在其他答案中所评论和解释的那样,您确实应该要求更改JSON格式。然而,有包含不同数据的元素列表并不罕见。对于这种情况,至少应该有一些字段指示要反序列化的数据类型。(并不是说这不是一种反模式,有时可能是)。
如果您达成了这个协议,就可以使用(例如)RuntimeTypeAdapterFactory,如链接问题中所述(抱歉,它是Java)。
否则你会遇到麻烦。隔离问题仍然很容易。不是说这很容易解决。我提出了一个可能的解决方案(再次抱歉,Java,但我想它很容易适应Kotlin)。我使用了许多内部静态类来使代码更加紧凑。实际的逻辑没有那么多行,大部分代码是将JSON映射到java类中。
使模型抽象化,使其不妨碍Gson在有问题的领域中完成其工作:
@Getter @Setter
public class Response {
private String status;
@Getter @Setter
public static class DataItem {
private Long id;
// below 2 rows explained later, this is what changes
@JsonAdapter(AnswerDataDeserializer.class)
private AnswerData answerData;
}
private DataItem[] data;
}
正如您所看到的,为了处理实际更复杂的内容,声明了以下内容:
public class AnswerDataDeserializer
implements JsonDeserializer<AnswerDataDeserializer.AnswerData> {
private final Gson gson = new Gson();
// The trick that makes the field more abstract. No necessarily
// needed answerData might possibly be just Object
public interface AnswerData {
// just to have something here not important
default String getType() {
return getClass().getName();
}
}
// here I have assumed Map<K,V> because of field name cannot be plain number.
@SuppressWarnings("serial")
public static class ChapterDataAnswer extends ArrayList<Map<Long, String>>
implements AnswerData {
}
@SuppressWarnings("serial")
public static class LiabilityDataAnswer
extends ArrayList<LiabilityDataAnswer.LiabilityData>
implements AnswerData {
@Getter @Setter
public static class LiabilityData {
private Long liabilityTypeId;
private Double monthlyPayment;
private Integer remainingMonth;
private String liabilityName;
private String name;
}
}
@Override
public AnswerData deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
if(json.isJsonArray()) {
try {
return gson.fromJson(json, ChapterDataAnswer.class);
} catch (Exception e) {
return gson.fromJson(json, LiabilityDataAnswer.class);
}
}
if(json.isJsonObject()) {
// do something else
}
return null;
}
}
上面我只介绍了两种更复杂的数组类型。但正如您所见,您必须以某种方式检查/查看所有反序列化的应答数据,以确定方法中的实际类型
现在您仍然需要了解不同类型的AnswerData
。也许有这样的类型以您无法确定类型的方式发生冲突。
注意:您也可以始终将整个内容或任何对象反序列化为映射或对象(如果我记得正确的话,Gson会将其设置为LinkedHashMap)
无论您是否这样做,在反序列化对象之后仍然需要检查对象的实例,并使用cast。
我从一个web服务调用中得到以下json响应。正如你所看到的,我们将得到什么类型的值作为响应,也是传入类型对象。 如何解析这个json 如何将解析后的值存储在数据库中,在数据库中我有一个包含列名、名称、值等的表 编辑: 目前,我正在将所有值转换为字符串,因为我们无法将布尔值添加到数据库中。 这是正确的方法吗?
其答复如下: 我相信问题出在响应前面的jsonFlickrApi上。 执行以下代码时: }
null 我的问题是如何为这种情况定义POJO类。 我试图用创建两个同名字段,但是抱怨POJO有重复的字段。
我在我的Spring引导webapp中配置了一个FaignClient,在那里我调用一个返回以下对象的外部api。 字段、和都是蛇型的。所有多字字段显示为空。有没有办法配置佯装客户端的Jackson解析器,使其能够处理蛇形字符?请注意,我无法更改spring boot webapp的默认Jackson解析器,因为我自己以驼峰格式呈现json。我只需要在我用来连接外部RESTAPI的假客户端上配置这
我想在eclipse IDE中使用Java编写1.18.2 Minecraft插件。我很确定我正在使用最新版本。我正在使用教程,当它说要把这个放进去时: 在JavaPlugin下面显示了一条红线,它说它不能被解析为一个类型。我应该导入这个: 导入组织。巴基特。插件。JAVAJavaPlugin 我在谷歌上搜索到的每一句话都把这个插口罐放在了项目属性中
问题内容: 我正在使用CURL发送请求。响应数据类型为。如何解析此数据并将其插入数据库? JSON输出: 问题答案: 如果您的变量是字符串json之类的,则必须使用function将其解析为 对象 或 数组 : 输出值 现在,您可以将变量作为数组使用: 参考文献: json_decode -PHP手册