Technology Sharing

java: How to convert a json string into a Map object, and ensure that its order remains unchanged.

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Everyone knows that the LinkedHashMap of Map objects is ordered, but its order can only guarantee the order of entry. If we convert a json string to a json object using JSONObject and force it to a LinkedHashMap, even if an ordered map is used, the result is still unordered. That's because when we convert from a string to a json object, it is already unordered. To solve the disorder problem, we can only start with converting it to a json object. When the json object is ordered, it will also be ordered when it is forced to be converted to a LinkedHashMap.

accomplish:
Import pom file

 <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <!--<version>2.17.1</version> 如果启动报错,可能有版本冲突,将版本号注释掉再试一下: 与jwt版本冲突-->
 </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

Packaging method:

/**
	有序的json转换
	字符串转换为LinkedHashMap
*/
public static Map<String,Object> toLinkedHashMap(String json) throws IOException{
	ObjectMapper mapper = new ObjectMapper();
	Map<String,Object> rmap = mapper.readValue(json, new TypeReference<LinkedHashMap<String,Object>(){});
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8