简介:写这个代码的本意是,最近需要使用JSONObject来根据一串JSON来获取参数,这是一些重复性的动作,于是萌生出大胆的想法:我能不能传入JSON后,让其自动帮我生成读取参数的代码呢,想了想感觉还是具有可行性的,动手试试,试试就试试。
我的解决方案:先去掉双引号,再将各组括号一一提取出来并且记录下来,我使用特殊字符串“##+数字+##”的形式来替代,最后得到一个精简版,以下面为例,原JSON变成{animals:##1##,address:xian,age:##2##}
,进入jSONChange2Code
处理,先去掉外围括号,再字符串处理一下就能得到各个key,就可以先输出,如果value不是特殊字符串就结束了,是的话就迭代处理进去,key也会被传进去,因为后面输出代码需要从这里get
package util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.regex.Pattern;
/**
* @ClassName: JSON2Code
* @Description:
*/
public class JSON2Code {
//存放内容
private static HashMap<String, String> hashMap = new HashMap<>();
public static void main(String[] args) throws IOException {
String jsonStr = "{\"animals\":{\"dog\":[{\"name\":\"Rufus\",\"breed\":\"labrador\",\"count\":1,\"twoFeet\":false},{\"name\":\"Marty\",\"breed\":\"whippet\",\"count\":1,\"twoFeet\":false}],\"cat\":{\"name\":\"Matilda\"}},\"address\":\"xian\",\"age\":[{\"dog_age\":10},{\"cat_age\":20}]}";
// 将双引号删除
jsonStr = jsonStr.replace("\"", "");
// 用来放生成的代码,写到工程根目录就好,方便看
String filePath = "MyCode.txt";
// 打开文件,没有该文件就自己创建文件
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
// 会清空原先的内容再重新写入
FileWriter fileWriter = new FileWriter(file);
//获取字符串的长度
int length = jsonStr.length();
String strTmp = null;
String[] strings = new String[length];
char charTmp = ' ';
char[] chars = new char[length];
//(1,length-1)用于首位两个大括号去掉
for (int i = 1; i < length - 1; i++) {
strTmp = String.valueOf(jsonStr.charAt(i));
charTmp = jsonStr.charAt(i);
strings[i] = strTmp;
chars[i] = ch