使用 Java 将 DynamoDB JSON 转换为标准 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43812278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:44:57  来源:igfitidea点击:

Converting DynamoDB JSON to Standard JSON with Java

javajsonamazon-dynamodb

提问by Nir

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:

我需要将 AWS DYNAMODB JSON 转换为标准 JSON 对象。所以我可以从 DynamoDB JSON 中删除数据类型更像是:

in DYNAMODB JSON:

在 DYNAMODB JSON 中:

"videos": [
    {
      "file": {
        "S": "file1.mp4"
      },
      "id": {
        "S": "1"
      },
      "canvas": {
        "S": "This is Canvas1"
      }
    },
    {
      "file": {
        "S": "main.mp4"
      },
      "id": {
        "S": "0"
      },
      "canvas": {
        "S": "this is a canvas"
      }
    }
  ]

to Standard JSON
 "videos": [
    {
      "file": "file1.mp4"
      ,
      "id": "1"
      ,
      "canvas":  "This is Canvas1"
      ,
      "file": "main.mp4"
      ,
      "id":  "0"
      ,
      "canvas": "this is a canvas"

    }
  ]

I found a nice tool in Javascript but is there any tool in Java in order to do that?

我在 Javascript 中找到了一个不错的工具,但是在 Java 中是否有任何工具可以做到这一点?

采纳答案by Himanshu Parmar

Below is the complete code for converting from Dynamo JSON to Standard JSON:

以下是从 Dynamo JSON 转换为标准 JSON 的完整代码:

import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.internal.InternalUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Main Lambda class to receive event stream, parse it to Survey
 * and process them.
 */
public class SurveyEventProcessor implements
        RequestHandler<DynamodbEvent, String> {

    private static final String INSERT = "INSERT";

    private static final String MODIFY = "MODIFY";

    public String handleRequest(DynamodbEvent ddbEvent, Context context) {

        List<Item> listOfItem = new ArrayList<>();
        List<Map<String, AttributeValue>> listOfMaps = null;
        for (DynamodbStreamRecord record : ddbEvent.getRecords()) {

            if (INSERT.equals(record.getEventName()) || MODIFY.equals(record.getEventName())) {
                listOfMaps = new ArrayList<Map<String, AttributeValue>>();
                listOfMaps.add(record.getDynamodb().getNewImage());
                listOfItem = InternalUtils.toItemList(listOfMaps);
            }

            System.out.println(listOfItem);
            try {
               // String json = new ObjectMapper().writeValueAsString(listOfItem.get(0));
                Gson gson = new Gson();
                Item item = listOfItem.get(0);

                String json = gson.toJson(item.asMap());
                System.out.println("JSON is ");
                System.out.println(json);
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
    }
} 

回答by shamanth Gowdra Shankaramurthy

You can use ItemUtilsclass in aws sdk. Below is sample code using Kotlin:

您可以在 aws sdk 中使用ItemUtils类。下面是使用 Kotlin 的示例代码:

import com.amazonaws.services.dynamodbv2.document.ItemUtils
import com.amazonaws.services.dynamodbv2.model.AttributeValue

fun main(args: Array<String>) {
    val data = HashMap<String,AttributeValue>()
    data.put("hello",AttributeValue().withS("world"))
    println(data.toString())
    println(ItemUtils.toItem(data).toJSON())
}

Output:

输出:

{hello={S: world,}}
{"hello":"world"}

回答by Harsh

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

以下是一个简单的解决方案,可用于将任何 DynamoDB Json 转换为简单 JSON。

//passing the reponse.getItems() 
public static Object getJson(List<Map<String,AttributeValue>> mapList) {
    List<Object> finalJson= new ArrayList();
    for(Map<String,AttributeValue> 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<String,Object> mapToJson(Map<String,AttributeValue> keyValueMap){
    Map<String,Object> finalKeyValueMap = new HashMap();
    for(Map.Entry<String, AttributeValue> 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.

这将以 List> 的形式生成您想要的 Json。然后使用 Gson 您可以将其转换为 Json 格式。

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

回答by mzimmermann

Amazon has an internal utility that can do the core of the job in 1 line.

亚马逊有一个内部实用程序,可以在 1 行中完成工作的核心。

Map<String, Object> jsonMapWithId = InternalUtils.toSimpleMapValue(attributeValueMap);

A long version which contains some configurations:

包含一些配置的长版本:

import com.amazonaws.services.dynamodbv2.document.internal.InternalUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.lang.Map;
import java.lang.HashMap;

public class JsonConvert {
    public static void main(String[] args) {
        Map<String,Object> jsonMap = new HashMap();
        jsonMap.put("string", "foo");
        jsonMap.put("number", 123);
        Map<String,Object> innerMap = new HashMap();
        innerMap.put("key", "value");
        jsonMap.put("map", innerMap);
        AttributeValue attributeValue = InternalUtils.toAttributeValue(jsonMap);
        Map<String, AttributeValue> attributeValueMap = new HashMap();
        attributeValueMap.put("id", attributeValue);

        Map<String, Object> jsonMapWithId = InternalUtils.toSimpleMapValue(attributeValueMap);
        Map<String, Object> jsonMap = jsonMapWithId.get("id"); // This is a regular map, values are not Amazon AttributeValue

        Gson gson = new Gson(); 
        String json = gson.toJson(jsonMap); 

        System.out.println(json);
    }
}

回答by Akshay Apte

Convert your JSON string to a Map first using

首先使用将您的 JSON 字符串转换为 Map

JSONObject jsonObj = new JSONObject(logString);
HashMap<String, Object> myMap = new Gson().fromJson(jsonObj.toString(), HashMap.class);

Function for converting DynamoDB JSON to Standard JSON

将 DynamoDB JSON 转换为标准 JSON 的函数

public static Map<String,Object> mapToJson(Map map){
        Map<String,Object> finalKeyValueMap = new HashMap();
        Iterator it = map.entrySet().iterator();

        while(it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();

            Map obj1 = (Map) pair.getValue();
            if(obj1.get("m") == null) {
                if(obj1.get("n") != null)
                    finalKeyValueMap.put(pair.getKey().toString(),obj1.get("n"));
                else if(obj1.get("s") != null)
                    finalKeyValueMap.put(pair.getKey().toString(),obj1.get("s"));
            }
            else {
                Map obj2 = (Map) pair.getValue();
                Map obj3 = (Map) obj2.get("m");
                finalKeyValueMap.put(pair.getKey().toString(),mapToJson(obj3));
            }

        }
        System.out.println(finalKeyValueMap.toString());
        return finalKeyValueMap;
    }

calling mapToJson(myMap);will return a standard Map which you can convert back to JSON

调用mapToJson(myMap);将返回一个标准 Map,您可以将其转换回 JSON