Home > Back-end >  How to convert String to Generics in java
How to convert String to Generics in java

Time:05-14

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?

CodePudding user response:

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

  • Related