-
-
Notifications
You must be signed in to change notification settings - Fork 258
/
GsonConfig.java
67 lines (58 loc) · 3.13 KB
/
GsonConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package de.luhmer.owncloudnewsreader.helper;
import android.graphics.BitmapFactory;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import de.luhmer.owncloudnewsreader.database.model.Feed;
import de.luhmer.owncloudnewsreader.database.model.Folder;
import de.luhmer.owncloudnewsreader.database.model.RssItem;
import de.luhmer.owncloudnewsreader.model.UserInfo;
import de.luhmer.owncloudnewsreader.reader.nextcloud.NextcloudDeserializer;
import de.luhmer.owncloudnewsreader.reader.nextcloud.Types;
import de.luhmer.owncloudnewsreader.ssl.OkHttpSSLClient;
/**
* Created by david on 27.06.17.
*/
public class GsonConfig {
public static Gson GetGson() {
Type feedList = new TypeToken<List<Feed>>() {}.getType();
Type folderList = new TypeToken<List<Folder>>() {}.getType();
Type rssItemsList = new TypeToken<List<RssItem>>() {}.getType();
// Info: RssItems are handled as a stream (to be more memory efficient - see @OwnCloudSyncService and @RssItemObservable)
return new GsonBuilder()
.setLenient()
.registerTypeAdapter(folderList, new NextcloudDeserializer<>(Types.FOLDERS.toString(), Folder.class))
.registerTypeAdapter(feedList, new NextcloudDeserializer<>(Types.FEEDS.toString(), Feed.class))
.registerTypeAdapter(rssItemsList, new NextcloudDeserializer<>(Types.ITEMS.toString(), RssItem.class))
.registerTypeAdapter(UserInfo.class, new JsonDeserializer<UserInfo>() {
@Override
public UserInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
JsonObject jObj = json.getAsJsonObject();
JsonElement avatar = jObj.get("avatar");
byte[] decodedString = {};
if (!avatar.isJsonNull()) {
decodedString = Base64.decode(avatar.getAsJsonObject().get("data").getAsString(), Base64.DEFAULT);
}
return new UserInfo.Builder()
.setDisplayName(jObj.get("displayName").getAsString())
.setUserId(jObj.get("userId").getAsString())
.setAvatar(BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length))
.setLastLoginTimestamp(jObj.get("lastLoginTimestamp").getAsLong())
.build();
} catch(IllegalStateException ex) {
throw OkHttpSSLClient.HandleExceptions(ex);
}
}
})
.create();
}
}