'How to convert String to Generics in java
I have a class similar to this:
public class Car<T> {
private T model;
private CarBodyParts body;
}
public class CarBodyParts {
private Integer carWidth;
private Integer carHeight;
}
public class Jaguar {
private String name;
private Integer wheelsCount;
}
String val = "{ "model": { "name": "Jaguar", "wheelsCount": 4 }, "body": { "carWidth": 100, "carHeight": 20 } }"
How can I convert this string val to Car<Jaguar>
object?
Solution 1:[1]
You can use Jackson library to convert the string to class. Add the below dependency to your project
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
Use the below code to convert the string to Car:
ObjectMapper objectMapper = new ObjectMapper();
String str = "{ \"model\": { \"name\": \"Jaguar\", \"wheelsCount\": 4 }, \"body\": { \"carWidth\": 100, \"carHeight\": 20 } }";
Car<Jaguar> car1 = objectMapper.readValue(str,Car.class);
Read more on jackson from here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prog_G |