您可以创建一个 POJO 类,然后使用 Jackson 或 Gson 等库将 JSON 字符串映射到 POJO 实例数组。在这种情况下,我将使用 Jackson,您可以通过 maven 将其导入:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.0</version>
</dependency>
POJO 类。请注意,我使用注解 @JsonProperty 来设置 JSON 字段名称,这样我就可以避免使用包含特殊字符的变量名称。
import com.fasterxml.jackson.annotation.JsonProperty;
public class APIResponse {
@JsonProperty("$id")
private int id;
@JsonProperty("accommodation_type")
private String accommodationType;
@JsonProperty("max_people")
private int maxPeople;
public int getId() {
return id;
}
public int getMaxPeople() {
return maxPeople;
}
public String getAccommodationType() {
return accommodationType;
}
@Override
public String toString() {
return "APIResponse{" +
"id=" + id +
", accommodationType='" + accommodationType + '\'' +
", maxPeople=" + maxPeople +
'}';
}
}
然后你可以反序列化使用:
final String json = "[{\"$id\":\"1\",\"accommodation_type\":\"apartment\",\"max_people\":2},{\"$id\":\"2\",\"accommodation_type\":\"lodge\",\"max_people\":5}]";
final ObjectMapper mapper = new ObjectMapper();
APIResponse[] responses = mapper.readValue(json, APIResponse[].class);
for (APIResponse response: responses) {
System.out.println(response.toString());
}
结果:
APIResponse{id=1, accommodationType='apartment', maxPeople=2}
APIResponse{id=2, accommodationType='lodge', maxPeople=5}
最后,您只需调用 POJO 类中的 getter 即可访问数据:
responses[0].getId(); // 1
responses[1].getAccommodationType; // lodge
如果你想用逗号分隔数据,请使用:
public String[] getByComas(APIResponse[] responses) {
List<String> data = new ArrayList<>();
for (APIResponse response: responses) {
data.add("id,");
data.add(response.getId() + ",");
data.add("accommodation_type,");
data.add(response.getAccommodationType() + ",");
data.add("max_people,");
data.add(response.getMaxPeople() + ",");
}
return data.toArray(new String[data.size()]);
}
然后只需使用:
String[] formattedMessage = getByComas(responses);
for (String s: formattedMessage) {
System.out.print(s);
}
结果:
id,1,accommodation_type,apartment,max_people,2,id,2,accommodation_type,lodge,max_people,5,
强烈建议使用 JSON 映射器,因为它们在解析 JSON 数据时非常可靠。
如果这能解决您的问题,请告诉我!