8

Typefactory class at jackson has many deprecated methods inside it. I am using it like that:

public List<T> getX(Class<T> clz) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        String jsonData = mapper.writeValueAsString(data);
        a = mapper.readValue(jsonData, TypeFactory.collectionType(List.class, clz));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return a;// a is a global variable
}

and it warns me that collectionType is deprecated. What to use instead of it?

Henrik Aasted Sørensen
  • 6,172
  • 9
  • 46
  • 56
kamaci
  • 65,625
  • 65
  • 210
  • 342
  • Use TypeReference instead. See this http://stackoverflow.com/questions/2525042/how-to-convert-a-json-string-to-a-mapstring-string-with-jackson-json accepted answer. [1]: – Varun Achar Nov 15 '11 at 09:02
  • I can not use generics with TypeReference – kamaci Nov 15 '11 at 09:19

1 Answers1

13

TypeFactory itself is NOT deprecated, just static methods; instance methods like "constructType" are available. So question is rather where do you get a TypeFactory instance to use.

Most often you get an instance from ObjectMapper using its getTypeFactory method; or from SerializationConfig / DeserializationConfig. They carry an instance around. If none of these works, there is TypeFactory.instance as well that you can use.

The reason for deprecation is that some extension modules will want to replace the standard factory: specifically, Scala module needs to extend type handling with Scala Collection (etc) types -- these will not work by default, since Scala does not extend java.util versions.

StaxMan
  • 102,903
  • 28
  • 190
  • 229
  • thanks for detailed explanation and voting up. I will test your sugesstion. Which one do you suggest `getTypeFactory` method from ObjectMapper or `TypeFactory.instance` or it doesn't important which one to use? – kamaci Nov 15 '11 at 20:48
  • Ideally ObjectMapper.getTypeFactory(), since that may have been overridden. But there is no point in constructing a new Mapper for getting access; so if you don't have mapper (or serialization/deserialization config), just use .instance. – StaxMan Nov 15 '11 at 22:17
  • I have a `mapper` variable and I do: `mapper.readValue(jsonData, mapper.getTypeFactory().collectionType(List.class, clz));` but still it is deprecated? – kamaci Nov 16 '11 at 06:25
  • 4
    collectionType() is static method; use `constructCollectionType` instead. – StaxMan Nov 16 '11 at 17:52
  • exactly what I need. Thanks for your help. – kamaci Nov 16 '11 at 21:09