一、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.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/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 {@Testpublic 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));}@Testpublic 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

六、效果演示

JSON与properties文件的相互转换相关推荐

  1. SpringBoot(12)---外部化配置(properties文件配置)

    SpringBoot特性_外部化配置(properties文件配置) SpringBoot允许将配置进行外部化(externalize),这样你就能够在不同的环境下使用相同的代码.你可以使用prope ...

  2. JAVA读取Properties文件对象常用方法总结

    实际开发中,总是会需要用到配置文件的,常用的就是properties.xml.json.比如,使用jdbc访问数据库时,我们就可以将driver.url.username.password这几个参数记 ...

  3. properties文件

    Java知识点总结:想看的可以从这里进入 目录 10.properties文件 10.1.properties文件 10.2.XML文件获取 10.3.注解获取 10.properties文件 10. ...

  4. java读写json格式的文件方法详解.txt,并批量存储进redis

    捐躯赴国难,视死忽如归.恸哭六军俱缟素,冲冠一怒为红颜.君子坦荡荡,小人长戚戚.风日晴和人意好,夕阳箫鼓几船归.民为贵,社稷次之,君为轻.Java 读写json格式的文件方法详解 文章录入:7747. ...

  5. Spring mail 邮件服务及其参数配置(properties文件的读写)

    一个Web 系统通常会少不了邮件服务的,比如用于注册,密码找回,订单提醒等应用场景.Spring 封装了一个简单易用的关于邮件发送的工具类JavaMailSenderImpl . 系统要提供邮件服务, ...

  6. pyspark —— spark dataframe 从hdfs读写文件:按照指定文件格式读写文件(读写csv、json、text文件,读取hive表,读取MySQL表)、按照指定分隔符读写文件

    spark有3种数据结构--RDD.DataFrame.DataSet.这里展示的文件读写方式,都是针对dataFrame数据结构的,也就是文件读进来之后,是一个spark dataFrame. 0. ...

  7. java中读取properties文件内容五种方式

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  8. Java Web的Maven项目中Properties文件的使用(2)

    为什么80%的码农都做不了架构师?>>>    背景 Java Web中常用一些Properties文件进行部署配置,其中如果在里面配置OS的路径,需要跨平台,主要就是考虑win系统 ...

  9. python json数据的文件读写操作

    python json数据的文件操作 代码 read_write_json.py #!/usr/bin/env python # -*- encoding: utf-8 -*- "" ...

最新文章

  1. 【Hibernate步步为营】--关联映射之多对一
  2. 二叉查找树(二)之 C++的实现
  3. 中通知设置响铃_主动切断干扰源——手机“通知”精细化管理
  4. 牛客提高R5 A.同余方程
  5. 关于程序、进程和线程
  6. 在线数理思维教育品牌“火花思维”完成4000万美元C轮融资
  7. matlab离散点包络,求大神指点绘制空间内散点图的包络面,,,散点程序如下
  8. 【2016-2017 ACM-ICPC, Egyptian Collegiate Programming Contest (ECPC 16) A】The game of Osho【SG函数+找规律】
  9. 说唱天王 Eminem 自传《The Way I am》1
  10. QuickTime 介绍 下载 安装(win7及以上版本)
  11. Java 读取Word文本框中的文本/图片/表格
  12. 28岁功能测试被辞,最后结局令人感慨...
  13. win10 uwp 关联文件
  14. JMP指令寻址方式总结,JMP BX指令寻址方式是什么
  15. 【我的反思】每一个选择都绝不是一无是处,也许是花,也许,是荆棘
  16. 浏览器主页被劫持到*.gndh666.top
  17. 基于JAVA建材公司管理系统计算机毕业设计源码+数据库+lw文档+系统+部署
  18. 计算机科学人生观和价值观,我的人生观和价值观
  19. 2021-2027年中国视频会议系统行业市场调研报告
  20. 【数学建模】2000全国大学生数学建模D题求解

热门文章

  1. 顺序表的定义及基本操作
  2. SQL开窗函数(窗口函数)详解
  3. scotland yard
  4. 微信小程序---文本域输入带最大字数限制
  5. Python科研数据分析专题之正态性检验
  6. No7. 字符串匹配
  7. Mysql数据库基本知识二:表的基础操作
  8. 关于安全防御方面的总结
  9. 服务器win10系统怎样共享,win10系统开启局域网共享
  10. 区块链-以太坊学习资料汇总