一、json文件
{
"id": 0,
"name": "kwok",
"pocket" : 33.33,
"wealth" : 1.23E9,
"isAdult": true,
"house": null,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {
"id": 1,
"name": "admin1",
"isAdult": false,
"house": null,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {
"id": 11,
"name": "admin11",
"isAdult": true,
"house": null,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {
"id": 111,
"name": "admin111",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
},
"friends": [{
"id": 112,
"name": "admin112",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{
"id": 1121,
"name": "admin1121",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
}]
}, {
"id": 113,
"name": "admin113",
"isAdult": true,
"house": null,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
}]
},
"friends": [{
"id": 2,
"name": "admin2",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
}, {
"id": 3,
"name": "admin3",
"isAdult": true,
"pages": [1, 2, 3],
"house": "yes",
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
}]
},
"friends": [{
"id": 2,
"name": "admin2",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {
"id": 22,
"name": "admin22",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
},
"friends": [{}]
}, {
"id": 3,
"name": "admin3",
"isAdult": true,
"pages": [1, 2, 3],
"pages_en": ["one", "two", "three"],
"mate": {},
"friends": [{}]
}]
}
二、pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:schemaLocation="http://maven./POM/4.0.0 https://maven./xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>json</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>json</name>
<description>json</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>pl.jalokim.propertiestojson</groupId>
<artifactId>java-properties-to-json</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.55</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
三、工具类
package com.example.json;
import org.json.JSONArray;
import org.json.JSONObject;
import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* JSON TO Properties
* Properties TO JSON
* JSON TO Map
* Map TO JSON
* Depend on stleary/JSON-java, mikolajmitura/java-properties-to-json.
* @author Kwok
*/
public class JSONParserUtils2 {
/**
* JSON TO Map
* @author Kwok
**/
public static Map<String,Object> jsonToMap(String jsonStr, String keyPrefix){
if(keyPrefix == null){
keyPrefix = "";
}
Map<String,Object> keyValueMap = new TreeMap<String,Object>();
/*
* 当值为字符串数组(如:"pages_en":["one","two","three"]),递归解析字符串时,会抛异常(如:JSON.parse("one") )。
* 这里进行异常捕获,按键值对进行储存。
* 详情查看 src/main/java/org/kwok/util/json/Test_OrgJson_Parse.java 。
*/
Object obj ;
try{
obj = new JSONObject(jsonStr);
}catch (Exception e1) {
try{
obj = new JSONArray(jsonStr);
}catch (Exception e2) {
obj = jsonStr;
}
}
if(obj instanceof JSONObject){
JSONObject jsonObject = new JSONObject(jsonStr);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
if(jsonObject.get(key) instanceof JSONObject){
String tempKeyPrefix = keyPrefix + key + ".";
keyValueMap.putAll(jsonToMap(jsonObject.get(key).toString(), tempKeyPrefix));
}else if(jsonObject.get(key) instanceof JSONArray){
String tempKeyPrefix = keyPrefix + key + ".";
keyValueMap.putAll(jsonToMap(jsonObject.get(key).toString(), tempKeyPrefix));
}else{
/*
* 处理属性值为 null 的情况,这里转为空字符串。
*/
if (jsonObject.get(key) == null) {
keyValueMap.put(keyPrefix + key, "");
} else {
keyValueMap.put(keyPrefix + key, jsonObject.get(key));
}
}
}
}else if(obj instanceof JSONArray){
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
String tempKeyPrefix = keyPrefix == "" ? keyPrefix + "[" + i + "]" + "." : keyPrefix.substring(0, keyPrefix.length() - 1) + "[" + i + "]" + ".";
/*
* 处理数组中元素为 null 的情况,这里转为空字符串。如:{"pages":[1,2,null]}。
*/
if (jsonArray.get(i) == null) {
keyValueMap.putAll(jsonToMap("", tempKeyPrefix));
} else {
keyValueMap.putAll(jsonToMap(jsonArray.get(i).toString(), tempKeyPrefix));
}
}
}else{
/*
* 当值为数组,递归时进入该分支。如:{"pages":[1,2,3]}。
*/
keyValueMap.put(keyPrefix == "" ? keyPrefix : keyPrefix.substring(0, keyPrefix.length() - 1), jsonStr);
}
return keyValueMap;
}
/**
* JSON TO Properties
* 注:由于 Properties 继承自 Hashtable,固 key、value 值均不可为 null。
* 详情查看 src/main/java/org/kwok/util/json/Test_Properties.java。
* @author Kwok
**/
public static Properties jsonToProperties(String jsonStr){
Properties properties = new Properties();
properties.putAll(jsonToMap(jsonStr, null));
return properties;
}
/**
* Map TO JSON
* @author Kwok
**/
public static String mapToJson(Map<String,Object> map){
return new PropertiesToJsonConverter().convertFromValuesAsObjectMap(map);
}
/**
* Properties TO JSON
* @author Kwok
**/
public static String propertiesToJson(Properties properties){
return new PropertiesToJsonConverter().convertToJson(properties);
}
}
四、测试类
package com.example.json.test;
import com.example.json.JSONParserUtils2;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
/**
* @author Kwok
*/
public class JSONParserUtils2Test {
@Test
public void jsonToMapTest() throws IOException{
Map<String,Object> map = JSONParserUtils2.jsonToMap(IOUtils.resourceToString("/test2.json",Charset.defaultCharset()), null);
Set<Entry<String, Object>> mapSet = map.entrySet();
for (Entry<String, Object> entry : mapSet) {
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
// System.out.println(JSONParserUtils2.mapToJson(map));
}
@Test
public void jsonToPropertiesTest() throws IOException{
Properties props = JSONParserUtils2.jsonToProperties(IOUtils.resourceToString("/test1.json",Charset.defaultCharset()));
Set<Entry<Object, Object>> propSet = props.entrySet();
for (Entry<Object, Object> entry : propSet) {
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
System.out.println(JSONParserUtils2.propertiesToJson(props));
}
}
五、原项目地址
链接: https://github.com/KwokRoot/java-json-to-properties.git
六、效果演示
|