尝试使用Jackson的ObjectMapper类手动将JSON字符串转换为对象,给出具体代码以及它的依赖
时间: 2023-06-19 22:08:14 浏览: 102
将json字符串转化为对象
使用Jackson的ObjectMapper类可以很方便地将JSON字符串转换为Java对象。以下是一个示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonToObject {
public static void main(String[] args) throws IOException {
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println(person.getName()); // John
System.out.println(person.getAge()); // 30
System.out.println(person.getCity()); // New York
}
}
class Person {
private String name;
private int age;
private String city;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
```
上述代码将JSON字符串 `{"name":"John","age":30,"city":"New York"}` 转换为 `Person` 对象,并打印出了对象中的属性值。
需要注意的是,使用Jackson需要添加相应的依赖,以下是Maven项目中的配置:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
```
阅读全文