簡體   English   中英

如何使用Retrofit將字節數組從Web api發送到android cliend

[英]How to send byte array from Web api to android cliend using Retrofit

我正在嘗試使用改造從web api到Android客戶端獲取模型。 該模型的一個屬性是字節數組,它不進行解析。 如果我包含該屬性,則整個模型返回null,否則它返回具有適當數據的模型。

我已經嘗試過這個解決方案如何在改進發送byte []數組 ,它們顯示如何從客戶端向服務器發送字節數組,但我需要的是完全相反的。

您可以使用此幫助程序類來序列化字節

public class GsonHelper {
    public static final Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class,
            new ByteArrayToBase64TypeAdapter()).create();

    // Using Android's base64 libraries. This can be replaced with any base64 library.
    private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
        public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return Base64.decode(json.getAsString(), Base64.NO_WRAP);
        }

        public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
        }
    }
}

致記: Orip

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM