You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中JSON转input.properties及HashMap转换全流程详解(附示例)

Hey there! Let's walk through exactly how to convert your sample JSON into a Java input.properties file and then load it into a nested HashMap. I'll break this down into clear, actionable steps with code examples.

Step-by-Step Guide: JSON → input.properties → Nested HashMap in Java

1. Convert JSON to input.properties File

Properties files use flat key-value pairs, so we'll map nested JSON structures using dot notation and array index brackets for lists. Here's how your sample JSON translates:

Sample JSON Recap

{ 
  "process_data": { 
    "input": { 
      "stockDetails": [{ 
        "prodName": "bag", 
        "Qty": "100" 
      }], 
      "totalcount": 100 
    } 
  } 
}

Final input.properties Structure

Create a file named input.properties in your Java project's resources folder with this content:

# input.properties
process_data.input.totalcount=100
process_data.input.stockDetails[0].prodName=bag
process_data.input.stockDetails[0].Qty=100
  • Nested JSON objects become dot-separated keys (e.g., process_data.input.totalcount)
  • Array elements use [index] notation (0-based) to represent list positions

2. Read input.properties into a Nested HashMap

We'll cover two approaches: manual parsing (great for learning) and using a library (simpler for production).

Option A: Manual Parsing (No External Libraries)

This code loads the properties file and builds a nested HashMap by splitting keys and handling array notation manually:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class PropertyLoader {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try (InputStream input = PropertyLoader.class.getClassLoader().getResourceAsStream("input.properties")) {
            if (input == null) {
                System.out.println("Sorry, unable to find input.properties");
                return;
            }
            properties.load(input);
            
            // Convert flat properties to nested HashMap
            Map<String, Object> nestedMap = convertToNestedMap(properties);
            System.out.println("Nested HashMap Output: " + nestedMap);
            
            // Access values directly
            int totalCount = (int) ((Map<String, Object>) ((Map<String, Object>) nestedMap.get("process_data")).get("input")).get("totalcount");
            System.out.println("Total Count: " + totalCount);
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static Map<String, Object> convertToNestedMap(Properties properties) {
        Map<String, Object> rootMap = new HashMap<>();
        
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            String[] keyParts = key.split("\\.");
            Map<String, Object> currentMap = rootMap;
            
            for (int i = 0; i < keyParts.length; i++) {
                String part = keyParts[i];
                
                // Handle array elements (e.g., stockDetails[0])
                if (part.contains("[") && part.contains("]")) {
                    String listName = part.substring(0, part.indexOf("["));
                    int index = Integer.parseInt(part.substring(part.indexOf("[") + 1, part.indexOf("]")));
                    
                    // Get or create the list in the current map
                    List<Map<String, Object>> list = currentMap.containsKey(listName) 
                        ? (List<Map<String, Object>>) currentMap.get(listName) 
                        : new ArrayList<>();
                    
                    // Ensure the list has enough elements to reach the index
                    while (list.size() <= index) {
                        list.add(new HashMap<>());
                    }
                    
                    // Move to the array element's map
                    currentMap = list.get(index);
                    currentMap.put(listName, list); // Attach the list back to its parent key
                } else {
                    // Handle regular nested keys
                    if (i == keyParts.length - 1) {
                        // Parse value to integer if possible, else keep as string
                        try {
                            currentMap.put(part, Integer.parseInt(value));
                        } catch (NumberFormatException e) {
                            currentMap.put(part, value);
                        }
                    } else {
                        // Create nested map if it doesn't exist
                        Map<String, Object> nestedMap = currentMap.containsKey(part) 
                            ? (Map<String, Object>) currentMap.get(part) 
                            : new HashMap<>();
                        currentMap.put(part, nestedMap);
                        currentMap = nestedMap;
                    }
                }
            }
        }
        return rootMap;
    }
}

Option B: Using Apache Commons Configuration (Simpler for Production)

For production code, use the Apache Commons Configuration library—it handles nested structures and arrays automatically, so you don't have to write parsing logic.

Step 1: Add Maven Dependency

Add this to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.8.0</version>
</dependency>

Step 2: Code to Load and Access Properties

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import java.util.Map;

public class PropertyLoaderWithCommons {
    public static void main(String[] args) {
        Configurations configs = new Configurations();
        try {
            PropertiesConfiguration config = configs.properties("input.properties");
            
            // Convert to nested HashMap directly
            Map<String, Object> nestedMap = config.getMap();
            System.out.println("Nested HashMap Output: " + nestedMap);
            
            // Access values with simple key paths
            int totalCount = config.getInt("process_data.input.totalcount");
            String prodName = config.getString("process_data.input.stockDetails[0].prodName");
            int qty = config.getInt("process_data.input.stockDetails[0].Qty");
            
            System.out.println("Total Count: " + totalCount);
            System.out.println("Product Name: " + prodName);
            System.out.println("Quantity: " + qty);
            
        } catch (ConfigurationException ex) {
            ex.printStackTrace();
        }
    }
}

Key Notes

  • Properties File Best Practices: Keep keys consistent with JSON structure, use meaningful names, and comment sections if needed.
  • Value Parsing: Both approaches can parse string values to integers (or other types) as shown—adjust based on your data types.
  • Library vs Manual: Use manual parsing for learning or small projects; use Apache Commons Configuration for production to handle edge cases robustly.

内容的提问来源于stack exchange,提问作者Süresh AK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:49