Home > Blockchain >  How can i use an unknown class or a list as a parameter in java?
How can i use an unknown class or a list as a parameter in java?

Time:11-25

I have a json response. I'm using Jackson to make Java Object from json response.

ObjectMapper objectMapper = new ObjectMapper();

    List<WorkPosition> workPositions = new ArrayList<>();

    try {
        workPositions = (List<WorkPosition>) objectMapper.readValue(response.body(), new TypeReference<List<WorkPosition>>() {});
    } catch (Exception e) {
        e.printStackTrace();
    }

And i want to create a class called Jackson and make this code a static method.

public class Jackson {

static ObjectMapper objectMapper = new ObjectMapper();

public static List<WorkPosition> parseList(String body){
    List<WorkPosition> list = new ArrayList<>();
    try {
        list = (ArrayList<WorkPosition>) objectMapper.readValue(body, new TypeReference<List<WorkPosition>>(){});
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return list;        
}

}

Above code only works for WorkPosition class. I want to make it available for all class. I have tried List<?>, T<>, and also tried to give as parameter the list that will return. But i didn't work it. How can this be done ?

CodePudding user response:

I don't think this is possible because what you are trying to make dynamic is the type parameter itself. Hence, the better way will be to have a method that can deserialize into any type and not just List.

So, if you have a method like this:

public static <T> T deser( String json, TypeReference<T> typeRef ){
    if( json == null || json.length() == 0 ) return null;
    try{
        return MAPPER.readValue( json, typeRef );
    }
    catch( IOException e ){
        throw new RuntimeException( e );
    }
}

where MAPPER is an instance of ObjectMapper, then it can be called from somewhere like this:

deser( "{<json-string-here>}", new TypeReference<ArrayList<SomeClass>>(){} );

This class can then be used even for non-List cases.

deser( "{<json-string-here>}", new TypeReference<SomeClass>(){} );

assuming that SomeClass has no-args constructor or a Jackson creator method.

  • Related