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

Java中如何自定义JSON字符串的键顺序(无需手动迭代)

Java: Reorder JSON Object Keys Without Manual Iteration

Great question! I totally get wanting to avoid writing clunky manual iteration logic—no one likes reinventing the wheel for basic tasks like this. Lucky for you, Java's most popular JSON libraries have built-in ways to handle ordered key reordering without the hassle. Below are two straightforward implementations using Jackson and Gson, the industry standards for JSON processing in Java.


Using Jackson Library

Jackson makes this easy by leveraging LinkedHashMap (which preserves insertion order) and its flexible serialization utilities. Here's how to reorder your JSON keys with minimal code:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.LinkedHashMap;
import java.util.List;

public class JsonKeyReorderer {
    public static void main(String[] args) throws Exception {
        // Your incoming JSON string
        String inputJson = "{ \"SignedSubscriptionRule\":{ \"User rights\":\"something1\", \"Function\":\"something2\", \"Method name\":\"something3\" }, \"CancelZeroSubscriptionRule\":{ \"User rights\":\"something4\", \"Function\":\"something5\", \"Method name\":\"something6\" }, \"NewLoanAllocationRule\":{ \"User rights\":\"something7\", \"Function\":\"something8\", \"Method name\":\"something9\" } }";

        // Define your desired key order
        List<String> targetKeyOrder = List.of(
            "SignedSubscriptionRule",
            "NewLoanAllocationRule",
            "CancelZeroSubscriptionRule"
        );

        ObjectMapper mapper = new ObjectMapper();
        // Disable auto-sorting of map keys to respect our custom order
        mapper.disable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);

        // Parse input into a LinkedHashMap (preserves original structure)
        LinkedHashMap<String, Object> originalJsonMap = mapper.readValue(inputJson, LinkedHashMap.class);

        // Build ordered map using the target list (no manual iteration beyond this concise loop)
        LinkedHashMap<String, Object> orderedJsonMap = new LinkedHashMap<>();
        targetKeyOrder.forEach(key -> orderedJsonMap.put(key, originalJsonMap.get(key)));

        // Convert back to formatted JSON string
        String orderedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(orderedJsonMap);
        System.out.println(orderedJson);
    }
}

Key Details:

  • We disable ORDER_MAP_ENTRIES_BY_KEYS to prevent Jackson from auto-sorting keys during serialization.
  • The forEach method on our target order list is a clean, built-in way to populate the ordered map—no messy loops with indices or conditionals required.

Using Gson Library

Gson also supports ordered map handling via LinkedHashMap. Here's a similarly simple implementation:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.LinkedHashMap;
import java.util.List;

public class GsonKeyReorderer {
    public static void main(String[] args) {
        String inputJson = "{ \"SignedSubscriptionRule\":{ \"User rights\":\"something1\", \"Function\":\"something2\", \"Method name\":\"something3\" }, \"CancelZeroSubscriptionRule\":{ \"User rights\":\"something4\", \"Function\":\"something5\", \"Method name\":\"something6\" }, \"NewLoanAllocationRule\":{ \"User rights\":\"something7\", \"Function\":\"something8\", \"Method name\":\"something9\" } }";

        List<String> targetKeyOrder = List.of(
            "SignedSubscriptionRule",
            "NewLoanAllocationRule",
            "CancelZeroSubscriptionRule"
        );

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        // Parse input into a LinkedHashMap to retain structure
        LinkedHashMap<String, Object> originalJsonMap = gson.fromJson(inputJson, new TypeToken<LinkedHashMap<String, Object>>(){}.getType());

        // Build ordered map using target order
        LinkedHashMap<String, Object> orderedJsonMap = new LinkedHashMap<>();
        targetKeyOrder.forEach(key -> orderedJsonMap.put(key, originalJsonMap.get(key)));

        // Convert back to JSON
        String orderedJson = gson.toJson(orderedJsonMap);
        System.out.println(orderedJson);
    }
}

Key Details:

  • The TypeToken is used to handle the generic map type correctly during deserialization.
  • Gson defaults to LinkedHashMap for generic map parsing, which helps preserve the original JSON structure while we reorder keys.

Why This Avoids Manual Iteration

Instead of writing custom loops to filter, sort, or rearrange keys from scratch, we're using:

  • Built-in Java collection classes (LinkedHashMap) that handle order preservation automatically.
  • Library utilities for parsing and serializing JSON, so we don't have to deal with low-level JSON token processing.
  • Concise, standard forEach operations (Java 8+) to populate the ordered map—this is far simpler than manual iteration logic.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:57:59