使用jackson字符串转jackson对象,使用jackson的get方法获取某个值
时间: 2023-09-28 20:07:17 浏览: 78
将json字符串转化为对象
假设我们有以下JSON字符串:
```
{
"name": "John",
"age": 30,
"isMarried": true,
"hobbies": [
"reading",
"swimming"
]
}
```
我们可以使用Jackson将其转换为Java对象:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"John\",\"age\":30,\"isMarried\":true,\"hobbies\":[\"reading\",\"swimming\"]}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
System.out.println(person.getName()); // John
System.out.println(person.getAge()); // 30
System.out.println(person.isMarried()); // true
System.out.println(person.getHobbies()); // [reading, swimming]
}
}
class Person {
private String name;
private int age;
private boolean isMarried;
private List<String> hobbies;
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 boolean isMarried() {
return isMarried;
}
public void setMarried(boolean isMarried) {
this.isMarried = isMarried;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
}
```
在上面的示例中,我们使用ObjectMapper的readValue()方法将JSON字符串转换为Java对象,然后使用该对象的getter方法获取特定的值。例如,我们使用person.getName()获取名称属性的值。
阅读全文