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

如何使用Java将JSON中Sections的字典格式转换为数组格式?

Convert Dictionary-style Sections to Array in Java

Alright, let's tackle this JSON transformation task. First, a quick correction: the target format you shared has a minor JSON syntax error—array elements can't be raw key-value pairs like "1":{}, they need to be wrapped in objects. So the valid target structure should look like this:

Input JSON

{
  "Sections": {
    "1": {"field1": "value1"},
    "2": {"field2": "value2"}
  }
}

Target Output JSON

{
  "Sections": [
    {"1": {"field1": "value1"}},
    {"2": {"field2": "value2"}}
  ]
}

We'll use Jackson (the most popular JSON processing library for Java) to handle this conversion. Here's how to do it:


Step 1: Add Jackson Dependency

If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest stable version -->
</dependency>

For Gradle:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'

Step 2: Conversion Code (Flexible, No Entity Classes)

If your JSON structure is dynamic (you don't know the exact fields in the section objects), use a generic map approach:

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

public class SectionTransformer {
    public static void main(String[] args) throws Exception {
        // Your input JSON string
        String inputJson = "{\"Sections\": {\"1\": {\"a\": \"b\"}, \"2\": {\"c\": \"d\"}}}";
        
        // Initialize Jackson's ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        
        // Parse input JSON into a generic map
        Map<String, Object> inputMap = objectMapper.readValue(inputJson, Map.class);
        
        // Extract the original Sections dictionary
        Map<String, Object> sectionsDict = (Map<String, Object>) inputMap.get("Sections");
        
        // Convert the dictionary to an array of single-entry objects
        List<Map<String, Object>> sectionsArray = new ArrayList<>();
        for (Map.Entry<String, Object> entry : sectionsDict.entrySet()) {
            Map<String, Object> singleSectionMap = new HashMap<>();
            singleSectionMap.put(entry.getKey(), entry.getValue());
            sectionsArray.add(singleSectionMap);
        }
        
        // Replace the original dictionary with the new array
        inputMap.put("Sections", sectionsArray);
        
        // Convert back to formatted JSON string
        String outputJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(inputMap);
        
        // Print or use the output
        System.out.println(outputJson);
    }
}

Step 3: Type-Safe Conversion (With Entity Classes)

If your section objects have a fixed structure, define entity classes for better type safety:

Define Entity Classes

// Represents the inner section object
class Section {
    private String field1;
    private String field2;
    
    // Getters and Setters
    public String getField1() { return field1; }
    public void setField1(String field1) { this.field1 = field1; }
    public String getField2() { return field2; }
    public void setField2(String field2) { this.field2 = field2; }
}

// Input DTO with dictionary-style Sections
class InputData {
    private Map<String, Section> Sections;
    
    // Getter and Setter
    public Map<String, Section> getSections() { return Sections; }
    public void setSections(Map<String, Section> sections) { Sections = sections; }
}

// Output DTO with array-style Sections
class OutputData {
    private List<Map<String, Section>> Sections;
    
    // Getter and Setter
    public List<Map<String, Section>> getSections() { return Sections; }
    public void setSections(List<Map<String, Section>> sections) { Sections = sections; }
}

Conversion Code

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

public class TypedSectionTransformer {
    public static void main(String[] args) throws Exception {
        String inputJson = "{\"Sections\": {\"1\": {\"field1\": \"value1\"}, \"2\": {\"field2\": \"value2\"}}}";
        
        ObjectMapper objectMapper = new ObjectMapper();
        InputData input = objectMapper.readValue(inputJson, InputData.class);
        
        OutputData output = new OutputData();
        List<Map<String, Section>> sectionsList = new ArrayList<>();
        
        for (Map.Entry<String, Section> entry : input.getSections().entrySet()) {
            Map<String, Section> sectionMap = new HashMap<>();
            sectionMap.put(entry.getKey(), entry.getValue());
            sectionsList.add(sectionMap);
        }
        
        output.setSections(sectionsList);
        
        String outputJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(output);
        System.out.println(outputJson);
    }
}

Both approaches will take your dictionary-style Sections and convert it into the array format you need. The generic approach is great for dynamic structures, while the typed approach is better for fixed, known JSON schemas.

内容的提问来源于stack exchange,提问作者Nir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:45:19