該賞金到期in 4天。回答這個問題有資格獲得 50聲望獎勵。 Muhammad Irfan想引起更多人對這個問題的關注:
Kotlin 或 Java 中是否有更好的方法來決議來自服務器的這種不同的 json 回應?
如何從 kotlin 中的 json 回應決議 answerData 鍵,因為它正在改變每個塊中的型別?我嘗試保留它 Any 但無法鍵入強制轉換。如何決議answerData?
{
"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"
}
]
}
]
}
uj5u.com熱心網友回復:
輸入 JSON 的設計很糟糕而且很難使用。讓我說:
- 它混合了
answerData屬性的元素和集合,并有許多反對它的缺點; - answer 元素缺少型別鑒別器欄位,因此反序列化必須分析每個 JSON 樹以生成一個有效的反序列化物件,并有另外十幾個缺點(包括“無法精確確定確切型別”和“它可能需要太多記憶體因為 JSON 樹");
- 一些工具,如 OpenAPI/Swagger,使用 discriminator 欄位反序列化為專用型別,而無需進行任何試探。
Any 當然不會為你作業,因為 Gson 甚至不知道這些有效載荷應該被反序列化成什么。
由于您沒有提供映射,我將提供我的映射示例,演示如何反序列化如此糟糕的 JSON 檔案。這還包括:
- 使用 Java 11 和 Lombok 而不是 Kotlin(因為正如您在通知中所述,這并不重要);
- 即使傳入的 JSON 節點包含物件而不是陣列,也可以將答案與答案串列進行映射以統一所有這些;
- 創建一個推斷解串器,它天真地做一些“魔術”來擺脫糟糕的 JSON 設計。
為了解決第一個問題,元素與陣列/串列,我在SO找到了一個現成的解決方案:
@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;
}
}
基本上,它不會自我推導,只會使用策略設計模式將過濾器和推導作業委托給其他地方。
現在讓我們假設您的映射足夠“通用”(包括使用@JsonAdapterforAnswer強制單個元素成為串列):
@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使用訪問者設計模式來避免顯式型別轉換。我不確定在使用密封類時如何在 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 ...
}
}
就是這樣。
我覺得這很困難,而且不必要地復雜。請讓您的服務器端伙伴修復他們的設計(請注意當前情況如何使反序列化比設計良好時更難)。
uj5u.com熱心網友回復:
正如其他答案中所評論和解釋的那樣,您確實應該要求更改 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;
}
如您所見,宣告了 thisAnswerData并@JsonAdapter用于處理實際更復雜的內容:
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 以確定方法中的實際型別deserialize
現在您仍然需要了解不同型別的AnswerData. 也許有這樣的型別會以一種您無法確定型別的方式發生沖突。
注意:您也可以隨時將整個內容或任何物件反序列化為Map或Object(LinkedHashMap如果我沒記錯的話,Gson 會成功)
無論您以何種方式執行此操作,您仍然需要在反序列化后檢查物件的實體并使用強制轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375646.html
