将json字符串转为java对象
时间: 2023-08-31 16:06:34 浏览: 96
可以使用Java中的Jackson库来实现将JSON字符串转换为Java对象。以下是一个示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToObject {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"John\", \"age\":30}";
ObjectMapper objectMapper = new ObjectMapper();
try {
Person person = objectMapper.readValue(jsonStr, Person.class);
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
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; }
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
```
在上面的代码中,我们使用ObjectMapper类的readValue()方法将JSON字符串转换为Person对象。注意,Person类必须具有与JSON对象键相同的属性。
阅读全文