Java可以使用Json庫來解析JSON數據。以下是使用Jackson庫來解析JSON數據的示例代碼:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParser {
public static void main(String[] args) {
String jsonData = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonData, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String city;
// 必須有無參數的構造方法
public Person() {}
// 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;
}
}
以上代碼將輸出:
Name: John
Age: 30
City: New York
這里使用了ObjectMapper類的readValue()方法來將JSON數據轉換為Person對象。Person類是一個簡單的POJO類,具有與JSON數據對應的屬性和相應的getter和setter方法。