Created
December 30, 2018 16:32
-
-
Save bekwam/ceda8017d196a89dcb794c4c8dde0184 to your computer and use it in GitHub Desktop.
Stream-Only Custom Gson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.*; | |
import org.apache.commons.lang3.tuple.Pair; | |
import java.lang.reflect.Type; | |
import java.util.List; | |
import java.util.stream.Collector; | |
// | |
// Converts a List of Pair<String, Long> into a JSON array of objects where the key of the Pair is | |
// field name "url" and the value is "fileSize" | |
// | |
public class FetchResultsSerializer implements JsonSerializer<List<Pair<String, Long>>> { | |
@Override | |
public JsonElement serialize(List<Pair<String, Long>> listOfPairs, Type type, JsonSerializationContext jsonSerializationContext) { | |
return listOfPairs.stream().map( | |
p -> { | |
JsonElement key = new JsonPrimitive(p.getKey()); | |
JsonElement value = new JsonPrimitive(p.getValue()); | |
JsonObject obj = new JsonObject(); | |
obj.add("url", key); | |
obj.add( "fileSize", value); | |
return obj; | |
} | |
).collect( | |
Collector.of( | |
() -> new JsonArray(), | |
(a, obj) -> a.add(obj), | |
(a, d) -> a | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment