如何用Java读取JSON文件动态在DynamoDB创建条目
Generic JSON to DynamoDB Loader (Supports Any Top-Level Objects)
Got it, the issue with your current code is that it's hardcoded to only handle ISA, GS, and ST keys. To make it work with any JSON structure, we need to dynamically iterate over all top-level key-value pairs in your JSON and create a separate DynamoDB item for each one.
Key Changes Needed:
- Ditch fixed key references and loop through all top-level field names in the JSON root
- Treat each top-level key as a unique item identifier (or part of your primary key)
- Store the corresponding JSON sub-object either as a serialized string, or split its fields into individual DynamoDB attributes (whichever fits your use case)
Refactored Full Code:
import java.io.File; import java.util.Iterator; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class LoadData { public static void main(String args[]) throws Exception { // Initialize DynamoDB client (keep your existing config) AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) .build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("NewTable"); // Read and parse the JSON file JsonParser parser = new JsonFactory().createParser(new File("C:\\Users\\Nikhil yadav\\Downloads\\healthclaims\\healthclaims\\src\\main\\resources\\output\\ValidJson.json")); JsonNode rootNode = new ObjectMapper().readTree(parser); ObjectMapper objectMapper = new ObjectMapper(); // Iterate over ALL top-level keys in the JSON Iterator<String> topLevelKeys = rootNode.fieldNames(); while (topLevelKeys.hasNext()) { String objectKey = topLevelKeys.next(); JsonNode objectValue = rootNode.get(objectKey); try { // Option 1: Store the entire sub-object as a cleaned string String cleanedValue = objectMapper.writeValueAsString(objectValue) .replaceAll("[^:a-zA-Z0-9_-|\\s]", " "); // Create item with the top-level key as primary key Item item = new Item() .withPrimaryKey("ObjectType", objectKey) .withString("ObjectData", cleanedValue); table.putItem(item); System.out.println("Successfully added item for: " + objectKey); } catch (Exception e) { System.err.println("Failed to add item for: " + objectKey); System.err.println("Error message: " + e.getMessage()); // Remove the 'break' if you want to continue processing other objects even if one fails // break; } } parser.close(); } }
Optional Enhancement: Split Sub-Object Fields into DynamoDB Attributes
If you don't want to store the sub-object as a single string, you can split its fields into individual attributes in the DynamoDB item. Replace the try block with this:
try { // Option 2: Split sub-object fields into individual DynamoDB attributes Item item = new Item().withPrimaryKey("ObjectType", objectKey); // Iterate over all fields in the sub-object Iterator<String> subFieldKeys = objectValue.fieldNames(); while (subFieldKeys.hasNext()) { String subKey = subFieldKeys.next(); JsonNode subValue = objectValue.get(subKey); // Handle different data types (adjust based on your JSON data) if (subValue.isTextual()) { item.withString(subKey, subValue.asText()); } else if (subValue.isNumber()) { if (subValue.isInt()) { item.withInt(subKey, subValue.asInt()); } else { item.withDouble(subKey, subValue.asDouble()); } } else if (subValue.isBoolean()) { item.withBoolean(subKey, subValue.asBoolean()); } } table.putItem(item); System.out.println("Successfully added item with split fields for: " + objectKey); }
How It Works:
- When you run this with your sample JSON, it will create 3 separate items in DynamoDB (one for ISA, one for GS, one for ST)
- If you pass a JSON with new top-level objects (like
XYZorCLAIM), it will automatically create items for those too—no code changes needed - The error handling is adjusted to optionally skip failed items instead of stopping the entire process
内容的提问来源于stack exchange,提问作者NikhilGandham
相关产品推荐
相关产品推荐

