json字符串转对象bean
时间: 2024-01-26 10:10:44 浏览: 116
js json字符串转对象
要将JSON字符串转换为Java对象,可以使用Jackson库。Jackson是一个流行的Java库,用于处理JSON数据。以下是使用Jackson将JSON字符串转换为Java对象的示例:
1.首先,需要将JSON字符串读入输入流中:
```
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
```
2.然后,使用ObjectMapper类的readValue方法将JSON字符串转换为Java对象:
```
Person person = objectMapper.readValue(inputStream, Person.class);
```
在这个例子中,Person是一个Java类,它的属性与JSON字符串中的字段相匹配。
完整示例代码:
```
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class JsonToObjectDemo {
public static void main(String[] args) throws IOException {
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
Person person = objectMapper.readValue(inputStream, Person.class);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.getCity());
}
}
class Person {
private String name;
private int age;
private String city;
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;
}
}
```
输出:
```
John
30
New York
```
阅读全文