Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varren/2578d8091bfad71c62b37138438451c5 to your computer and use it in GitHub Desktop.
Save varren/2578d8091bfad71c62b37138438451c5 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.io.IOException;
import java.util.List;
/**
* Created by varren on 16.10.17.
*/
public class Main15 {
private static String json = "{\n" +
" \"Level1\": {\n" +
" \"Level2\": {\n" +
" \"Level3\": {\n" +
" \"genericObject\": [\n" +
" { \n" +
" \"attribute1\": \"a\", \n" +
" \"attribute2\": \"b\"\n" +
" },\n" +
" { \n" +
" \"attribute1\": \"c\", \n" +
" \"attribute2\": \"d\"\n" +
" } \n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
private static String json2= "{\n" +
" \"Level1\": {\n" +
" \"Level2\": {\n" +
" \"Level3\": {\n" +
" \"genericObject\": [\"attribute1\",\"attribute2\",\"attribute3\",\"attribute4\"]\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
public static void main(String[] args) throws IOException {
test(SomeObject.class, json);
test(String.class, json2);
}
private static void test(Class<?> c, String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// because we dont have object above Level1 so lvl1 is a field of root object
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(Level1.class, c);
System.out.println((Level1)mapper.readValue(json, javaType));
}
static class Level1<T> {
@JsonProperty("Level2")
public Level2<T> l2;
@Override
public String toString() {
return "Level1{" +
"l2=" + l2 +
'}';
}
}
static class Level2<T> {
@JsonProperty("Level3")
public Level3<T> l3;
@Override
public String toString() {
return "Level2{" +
"l3=" + l3 +
'}';
}
}
static class Level3<T> {
@JsonProperty("genericObject")
public List<T> objectsList;
@Override
public String toString() {
return "Level3{" +
"objectsList=" + objectsList +
'}';
}
}
static class SomeObject{
public String attribute1;
public String attribute2;
@Override
public String toString() {
return "SomeObject{" +
"attribute1='" + attribute1 + '\'' +
", attribute2='" + attribute2 + '\'' +
'}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment