Skip to content

Instantly share code, notes, and snippets.

@iljaosintsev
Created October 1, 2018 17:54
Show Gist options
  • Save iljaosintsev/4b912a2a2ab26fb36eee02f0823f5768 to your computer and use it in GitHub Desktop.
Save iljaosintsev/4b912a2a2ab26fb36eee02f0823f5768 to your computer and use it in GitHub Desktop.
Gson and generic
package com.turlir.abakgists;
import com.google.gson.Gson;
import org.junit.Test;
import java.util.Objects;
import static org.junit.Assert.*;
public class Demo {
@Test
public void test() {
ApiResponse<Model> mr = new ModelResponse(new Model("str", 5));
mr.code = 5.5f;
Gson gson = new Gson();
String json = gson.toJson(mr);
assertEquals("{\"payload\":{\"str\":\"str\",\"index\":5},\"code\":5.5}", json);
ApiResponse<Model> resp = gson.fromJson(json, ModelResponse.class);
assertEquals(mr, resp);
}
private static class ApiResponse<T> {
T payload;
float code;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ApiResponse<?> that = (ApiResponse<?>) o;
return Float.compare(that.code, code) == 0 &&
Objects.equals(payload, that.payload);
}
@Override
public int hashCode() {
return Objects.hash(payload, code);
}
}
private static class ModelResponse extends ApiResponse<Model> {
ModelResponse(Model model) {
payload = model;
}
}
private static class Model {
final String str;
final int index;
Model(String str, int index) {
this.str = str;
this.index = index;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Model model = (Model) o;
return index == model.index &&
Objects.equals(str, model.str);
}
@Override
public int hashCode() {
return Objects.hash(str, index);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment