如何在 java 中将字符串转换为泛型
How to convert String to Generics in java
我有一个 class 与此类似:
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 } }" =15=]
如何将此字符串 val 转换为 Car<Jaguar>
对象?
您可以使用 Jackson 库将字符串转换为 class。
将以下依赖项添加到您的项目
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
使用下面的代码将字符串转换为 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);
从 here
阅读更多关于杰克逊的信息
我有一个 class 与此类似:
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 } }" =15=]
如何将此字符串 val 转换为 Car<Jaguar>
对象?
您可以使用 Jackson 库将字符串转换为 class。 将以下依赖项添加到您的项目
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
使用下面的代码将字符串转换为 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);
从 here
阅读更多关于杰克逊的信息