gson 使用java8将列表行的值组合为逗号,逗号由其键分隔

daolsyd0  于 2023-08-05  发布在  Java
关注(0)|答案(1)|浏览(151)

我的输入是一个具有动态属性和值的JsonArray。

[
 {
  "id": "1",
  "name": "abc",
  "gender": "F"
 },
{
  "id": "2",
  "name": "dgc",
  "address": "MDU"
 },{
  "id": "3",
  "name": "ghf",
  "gender": "M"
 },
]

字符串
预期输出如下:

{
"id": "1,2,3",
"name": "abc,dgc,ghf",
"gender": "F,M" 
"address":"MDU"
}


我期待的逻辑将读取JsonArray中的动态属性,并将值组合为逗号分隔的值。通过使用这些值,需要创建一个带有key的JsonObject。

2eafrhcq

2eafrhcq1#

这个应该能用

public JsonNode test() throws JsonProcessingException {
        String jsonArray = "[\n" +
                " {\n" +
                "  \"id\": \"1\",\n" +
                "  \"name\": \"abc\",\n" +
                "  \"gender\": \"F\"\n" +
                " },\n" +
                "{\n" +
                "  \"id\": \"2\",\n" +
                "  \"name\": \"dgc\",\n" +
                "  \"address\": \"MDU\"\n" +
                " },\n" +
                " {\n" +
                "  \"id\": \"3\",\n" +
                "  \"name\": \"ghf\",\n" +
                "  \"gender\": \"M\"\n" +
                " }\n" +
                "]";

        // Parse the JSON array
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonArray);

        // Create a map to hold the combined values
        Map<String, String> combinedValues = new HashMap<>();

        // Iterate over the JSON array and combine values
        Iterator<JsonNode> iterator = jsonNode.iterator();
        while (iterator.hasNext()) {
            JsonNode item = iterator.next();
            item.fields().forEachRemaining(entry -> {
                String key = entry.getKey();
                String value = entry.getValue().asText();
                combinedValues.merge(key, value, (v1, v2) -> v1 + "," + v2);
            });
        }

        // Create the resulting JSON object
        return objectMapper.valueToTree(combinedValues);

    }

字符串

相关问题