@TOCJSON对象遍历并按照原顺序输出
需求
在工作中,往往遇会遇到对JSON对象的处理,在这里记录一下我需要遍历JSON对象,并对JSON中的每一个加密字段进行解密,并将解密后的JSON元素按照原顺序进行输出。
Java代码
package test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.io.*;
import java.util.Map;
/**
* 遍历JSON object,并保证元素顺序不变。
* 用于多JSON 对象的字段的处理
*/
public class JsonLoop {
/**
* 读取测试的JSON字符串并按照元素在JSON字符串中的顺序转换成JSON对象
*
* @return
*/
public static JSONObject getObject() {
char cbuf[] = new char[10000];
InputStreamReader input = null;
try {
input = new InputStreamReader(new FileInputStream(new File("src/main/java/test/test.json")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int len = 0;
try {
len = input.read(cbuf);
} catch (IOException e) {
e.printStackTrace();
}
String text = new String(cbuf, 0, len);
//1.构造一个json对象,在这里确保JSON对象中元素的顺序和JSONString中的数据不变
JSONObject obj = JSONObject.parseObject(text, Feature.OrderedField);
return obj;
}
/**
* 遍历JSON对象,对字段进行某种出处理
*
* @param object
* @return
*/
public static JSONObject jsonLoop(Object object) {
JSONObject newJson = new JSONObject(true);
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
Object o = entry.getValue();
String key = entry.getKey();
if (o instanceof String) {
String vaule = (String) o;
newJson.put(key, vaule);
} else if (o instanceof Integer) {
int vaule = (int) o;
newJson.put(key, vaule);
} else if (o instanceof Boolean) {
boolean vaule = (boolean) o;
newJson.put(key, vaule);
} else if (o instanceof Double) {
double vaule = (double) o;
newJson.put(key, vaule);
} else if (o instanceof Float) {
float vaule = (float) o;
newJson.put(key, vaule);
} else if (o instanceof Long) {
long vaule = (long) o;
newJson.put(key, vaule);
} else if (o instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) o;
JSONArray newJArray = new JSONArray();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject sub = jsonLoop(jsonArray.get(i));
newJArray.add(sub);
}
newJson.put(key, newJArray);
} else if (o instanceof JSONObject) {
JSONObject sub = jsonLoop(o);
newJson.put(key, sub);
} else {
newJson.put(key, o);
}
}
}
return newJson;
}
public static void main(String[] args) {
JSONObject jsonObject = getObject();
System.out.println(jsonObject.toJSONString());
System.out.println();
JSONObject newJson = jsonLoop(jsonObject);
System.out.println(newJson.toJSONString());
}
}
测试数据
{
"test1": "wx9fdb8ble7ce3c68f",
"test2": "123456789",
"testData1": {
"testdatason1": "97895455",
"testdatason2": 3,
"testData2": [
{
"testshuzu1": "12",
"testshuzu1": "11"
},
{
"testshuzu2": "13",
"testshuzu2": "14"
},
{
"testshuzu3": "15",
"testshuzu3": "16"
}
]
}
}