Java中动态Map动态JSON数据转换

jfewjypa  于 2023-01-15  发布在  Java
关注(0)|答案(1)|浏览(149)

我一直坚持的问题,我想做动态Map的JSON数据,这也是不断变化的问题是:假设数据来自API,所以我已经创建了演示数据

{
    "api1": [
        {
            "jid":101,
            "clientName":"ABC"
        },
        {
            "jid": 102,
            "clientName": "XYZ"
        }
    ],
    "api2":[
        {
            "jobId":1101,
            "jClientName": "ABCD"
        },
        {
            "jobId": 1102,
            "jClientName": "XYZA"
        }
    ],
    "api3":[
        {
            "id":19001,
            "jobCName":"ABCDEF"
        },
        {
            "id": 19002,
            "jobCName": "PQRSTU"
        }
    ]
}

在该数据中,每个API具有2个记录。我想要将数据Map成以下给定格式,

[
    {
        "jobid":101,
        "clientName":"ABC"
    },
    {
        "jobid": 102,
        "clientName": "ABCD"
    },
    {
        "jobid": 1101,
        "clientName": "ABCDEF"
    }
]

因此,所有数据都应正确Map,第一个API具有clientName,第二个api具有jClientName,第三个api具有jobCName。这些字段可以是动态,但我希望它们在clientName列中正确Map。我如何解决此问题,应该采取什么方法或做什么
需要此格式的响应,即每个字段应正确Map,预期输出为:

[
    {
        "jobid":101,
        "clientName":"ABC"
    },
    {
        "jobid": 102,
        "clientName": "ABCD"
    },
    {
        "jobid": 1101,
        "clientName": "ABCDEF"
    }
]

对此应该实现什么逻辑

gcmastyq

gcmastyq1#

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonData = mapper.readTree(jsonString);

        List<Map<String, String>> finalData = new ArrayList<>();
        for (JsonNode apiData : jsonData) {
            for (JsonNode record : apiData) {
                Map<String, String> data = new HashMap<>();
                if (record.has("jid")) {
                    data.put("jobid", record.get("jid").asText());
                    data.put("clientName", record.get("clientName").asText());
                } else if (record.has("jobId")) {
                    data.put("jobid", record.get("jobId").asText());
                    data.put("clientName", record.get("jClientName").asText());
                } else if (record.has("id")) {
                    data.put("jobid", record.get("id").asText());
                    data.put("clientName", record.get("jobCName").asText());
                }
                finalData.add(data);
            }
        }

        System.out.println(finalData);
    }
}

相关问题