java json转对象
时间: 2024-12-24 22:10:35 浏览: 3
在Java中,你可以使用`org.json.JSONObject`或`com.fasterxml.jackson.databind.ObjectMapper`等库来将JSON字符串转换为Java对象。这里以`JSONObject`为例:
假设你有一个简单的JSON字符串如下:
```json
{
"name": "张三",
"age": 30,
"city": "北京"
}
```
对应的Java类可能是这样的:
```java
public class Person {
private String name;
private int age;
private String city;
// getters and setters...
}
```
要将其转换为`Person`对象,可以这样做:
```java
String jsonString = "{\"name\":\"张三\",\"age\":30,\"city\":\"北京\"}";
JSONObject jsonObject = new JSONObject(jsonString);
Person person = new Person();
person.setName(jsonObject.getString("name"));
person.setAge(jsonObject.getInt("age"));
person.setCity(jsonObject.getString("city"));
// 或者使用Jackson库:
ObjectMapper mapper = new ObjectMapper();
Person personFromJson = mapper.readValue(jsonString, Person.class);
```
阅读全文