简体   繁体   English

将 Json 响应格式化为数组 Java

[英]Formatting Json Response into an Array Java

Currently I am receiving a response like this from my API:目前我从我的 API 收到这样的回复:

[{"$id":"1","accommodation_type":"apartment","max_people":2},{"$id":"2","accommodation_type":"lodge","max_people":5}]

I would like to format it so that the output removes all the unnecessary punctuation so that it looks more like this whilst also placing it into an Array.我想对其进行格式化,以便 output 删除所有不必要的标点符号,使其看起来更像这样,同时也将其放入数组中。

id, 1, accommodation_type, apartment, max_people, 2, id, 2, accommodation_type, lodge, max_people 5

OR要么

1, apartment, 2, ,2, lodge, 5

Currently I have tried:目前我已经尝试过:

String temp[]= AccommodationTypesStr.split(":|\\,|\\}"); // Where AccommodationTypesStr is the input json string

However between each row of data it leaves a empty space as a element in the array so its like:但是,在每行数据之间,它会留下一个空白空间作为数组中的一个元素,因此它是这样的:

id, 1, accomodation_type, apartment, max_people, 2,  ,id, 2, accommodation_type, lodge, max_people 5

Whilst also still having some brackets in the response.同时在响应中仍然有一些括号。

I've messed around with JSON Object and Array but had no luck at all so was wondering if I could do it by formatting it myself.我搞砸了 JSON Object 和 Array 但一点运气都没有,所以想知道我是否可以通过自己格式化来做到这一点。

You can use ObjectMapper to convert json string to some object, in this case like List<Map<String, Object>> .您可以使用ObjectMapperjson字符串转换为一些 object,在本例中为List<Map<String, Object>> Then iterate over this list using java stream api .然后使用java stream api遍历此列表。

Maven dependency: Maven 依赖:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

Read json string value:读取json字符串值:

String json = "[{\"$id\":\"1\",\"accommodation_type\":\"apartment\",\"max_people\":2},{\"$id\":\"2\",\"accommodation_type\":\"lodge\",\"max_people\":5}]";
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> list = mapper.readValue(json, List.class);

Then iterate over this list:然后迭代这个列表:

List<Object> flatList = list.stream()
    .flatMap(element -> element.values().stream())
    .collect(Collectors.toList());

System.out.println(flatList); // [1, apartment, 2, 2, lodge, 5]

Or more detailed variant:或更详细的变体:

List<Object> flatList = list.stream()
    .map(Map::values)
    .collect(Collectors.toList());

System.out.println(flatList); // [[1, apartment, 2], [2, lodge, 5]]

And more:和更多:

List<Object> flatList = list.stream()
    .flatMap(element -> element.entrySet().stream())
    .flatMap(entry -> Stream.of(
        entry.getKey().replace("$", ""), // without "$"
        entry.getValue()))
    .collect(Collectors.toList());

System.out.println(flatList);
// [id, 1, accommodation_type, apartment, max_people, 2, id, 2, accommodation_type, lodge, max_people, 5]

In general, you can write your own flattening algorithm.通常,您可以编写自己的展平算法。 For example:例如:

You can create a POJO class and then use libraries like Jackson or Gson to map the JSON string into an array of POJO instances.您可以创建一个 POJO class,然后使用 Jackson 或 Gson 到 map 等库将 JSON 字符串放入 POJO 实例数组中。 In this case I will use Jackson you can import it via maven with:在这种情况下,我将使用 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>

The POJO class. Note that I use the annotation @JsonProperty to set the JSON field names so I can avoid using variable names that contain special characters. POJO class。请注意,我使用注释@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 +
                '}';
    }
}

Then you can deserialize using:然后你可以反序列化使用:

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());
}

Result:结果:

APIResponse{id=1, accommodationType='apartment', maxPeople=2}
APIResponse{id=2, accommodationType='lodge', maxPeople=5}

Finally, you can access the data just by calling the getters in the POJO class:最后,您只需调用 POJO class 中的 getter 即可访问数据:

responses[0].getId(); // 1
responses[1].getAccommodationType; // lodge

Then if you want the data separated by commas use:然后,如果您想要用逗号分隔的数据,请使用:

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()]);
}

Then just use:然后只需使用:

String[] formattedMessage = getByComas(responses);
for (String s: formattedMessage) {
    System.out.print(s);
}

Result:结果:

id,1,accommodation_type,apartment,max_people,2,id,2,accommodation_type,lodge,max_people,5,

Using JSON mappers is highly recommended as they are pretty reliable when parsing JSON data.强烈建议使用 JSON 映射器,因为它们在解析 JSON 数据时非常可靠。

Let me know if this solves your problem!如果这能解决您的问题,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM