I have this string
String str= " {\"name\":\"xyz\",\"id\":\"123\" } ";
I want to extract xyz
from the given string, can someone please suggest an efficient way of doing it in Java?
Step1 : Create Some DTO class like below
public class MyDTO{
private String name;
private String id;
// Create setters and getters
}
Step2 : Convert above string to DTO(pojo class) class by using objectmapper like below
ObjectMapper objectMapper = new ObjectMapper();
String str= "{\"name\":\"xyz\",\"id\":\"123\"}";
MyDTO dto = objectMapper.readValue(str, MyDTO.class);
Step3 : After converting to DTO object you can use it with dto object like below.
System.out.println(dto.getName());
Note : If you don't have fasterxml dependency in your pom file then add the below dependency to your pom file.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
Happy coading..!
If you don't want to parse the whole JSON into an object, you can do this with JsonPath .
String str = " {\"name\":\"xyz\",\"id\":\"123\" } ";
String name = JsonPath.read(str,"$.name");
System.out.println(name);
Add the following dependency to your pom.xml
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.5.0</version>
</dependency>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.