Converting DynamoDB JSON to Standard JSON with Java

后端 未结 5 919
说谎
说谎 2020-12-16 06:36

I need to convert a AWS DYNAMODB JSON to a standard JSON object. so I can remove the data type from the DynamoDB JSON Something more like:

in DYNAMODB JSON:

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 07:25

    Following is a simple solution which can be applied to convert any DynamoDB Json to Simple JSON.

    //passing the reponse.getItems() 
    public static Object getJson(List> mapList) {
        List finalJson= new ArrayList();
        for(Map eachEntry : mapList) {
            finalJson.add(mapToJson(eachEntry));
        }
        return finalJson;
    }
    
    
    //if the map is null then it add the key and value(string) in the finalKeyValueMap
    public static Map mapToJson(Map keyValueMap){
        Map finalKeyValueMap = new HashMap();
        for(Map.Entry entry : keyValueMap.entrySet()) 
        {
            if(entry.getValue().getM() == null) {
                finalKeyValueMap.put(entry.getKey(),entry.getValue().getS());
            }
            else {
                finalKeyValueMap.put(entry.getKey(),mapToJson(entry.getValue().getM()));
            }
        }
        return finalKeyValueMap;
    }
    
    
    

    This will produce your desired Json in the form of List>. Then using the Gson you can convert it into the Json format.

    Gson gson = new Gson();
    String jsonString = gson.toJson(getJson(response.getItems()));
    

    提交回复
    热议问题