Q
如何使用杰克逊
73
A
回答
118
我终于明白了:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
68
对方回答是正确的,但为了完整性,这里有其他的方法:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
3
完整的例子使用数组。 替换 “constructArrayType()”,由 “constructCollectionType()” 或其它任何你需要的类型。
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class Sorting {
private String property;
private String direction;
public Sorting() {
}
public Sorting(String property, String direction) {
this.property = property;
this.direction = direction;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public static void main(String[] args) throws JsonParseException, IOException {
final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
ObjectMapper mapper = new ObjectMapper();
Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
System.out.println(sortings);
}
}
相关问题
- 1. 如何使用杰克逊
- 2. 如何使用杰克逊
- 3. 使用杰克逊
- 4. 使用杰克逊
- 5. 使用杰克逊
- 6. 使用杰克逊
- 7. 使用杰克逊
- 8. 杰克逊2.0杰克逊1.x的
- 9. 如何使用杰克逊泛型
- 10. 如何使用杰克逊得到JsonProcessingException
- 11. 如何使用杰克逊映射
- 12. 如何使用杰克逊库
- 13. 无法使用杰克逊
- 14. 阅读使用杰克逊
- 15. 使用杰克逊的java
- 16. 同时使用杰克逊
- 17. 使用杰克逊ObjectWriter
- 18. 杰克逊不使用setter
- 19. 无法使用杰克逊
- 20. 如何与杰克逊
- 21. 如何不杰克逊
- 22. 如何与杰克逊
- 23. 杰克逊
- 24. 杰克逊Deserialising:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
- 25. 与杰克逊
- 26. 与杰克逊
- 27. 与杰克逊
- 28. 杰克逊UnrecognizedPropertyException
- 29. 与杰克逊
- 30. 与杰克逊
我有类似的情况,但决定将它解序列化为JSONArray对象,而不是将它转换为类,因为它将避免将来出现类序列化问题。我有什么好处吗? – Arun