Java中如何自定义JSON字符串的键顺序(无需手动迭代)
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_KEYSto prevent Jackson from auto-sorting keys during serialization. - The
forEachmethod 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
TypeTokenis used to handle the generic map type correctly during deserialization. - Gson defaults to
LinkedHashMapfor 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
forEachoperations (Java 8+) to populate the ordered map—this is far simpler than manual iteration logic.
内容的提问来源于stack exchange,提问作者Sabina Orazem

