A Generic method to modify the names in a JSONObject
来源:互联网 发布:软件注册权登记 编辑:程序博客网 时间:2024/05/21 04:43
This is a method to use configuration to modify the filed names of a JSON string.
You can use this function to do the following work:
1. rename a field of the JSON string
2. delete a field which not needed
3. rename a nested sub-JSON field
The logic is like this:
1. Take a configuration file which is a JSON string and convert it into JSONObject. An incomingKey you defined here means this field or it's sub-fields are needed to be modified.
2. Read the JSON string which need to be modified as input.
3. Call the method to do the rename work, , loop all the fields of the configuration JOSNObject, use ecah of the incomingKey to get the object, if needRemoval is true, then delete this field. if needRemoval is false, and the outgoingKey exsits, then rename this field.
4. Do regression, until all the fields in the configuration file are done.
Here comes the code.
package com.judd.tools;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import static net.sf.json.JSONObject.fromObject;public class JSONRenameUtils {public static String renameJSONFields(String rawJSONString) throws Exception {JSONObject mapJSONObject = JSONNameMappingLoader.getNameMappings();JSONObject rawJSONObject = fromObject(rawJSONString);doRenameWork(rawJSONObject, mapJSONObject);return rawJSONObject.toString();}private static void doRenameWork(JSONObject targetObj, JSONObject mapObj) {if (mapObj.containsKey(Consts.SUB_JSON_OBJECT)) {JSONArray children = (JSONArray) mapObj.get(Consts.SUB_JSON_OBJECT);for (Object obj : children.toArray()) {JSONObject jsonObj = (JSONObject) obj;String incomingKey = jsonObj.optString(Consts.INCOMING_KEY);String outgoingKey = null;boolean needRemoval = Boolean.valueOf(jsonObj.optString(Consts.NEED_REMOVAL));;if (jsonObj.containsKey(Consts.OUTGOING_KEY)) {outgoingKey = jsonObj.optString(Consts.OUTGOING_KEY);}if (needRemoval) {targetObj.remove(incomingKey);continue;}Object removed = targetObj.get(incomingKey);if (outgoingKey != null) {targetObj.remove(incomingKey);targetObj.put(outgoingKey, removed);} else {removed = targetObj.get(incomingKey);}if (removed instanceof JSONObject) {doRenameWork((JSONObject) removed, jsonObj);if (outgoingKey != null) {targetObj.put(outgoingKey, removed);} else {targetObj.put(incomingKey, removed);}}else if(removed instanceof JSONArray){for (Object object : ((JSONArray)removed).toArray()) {JSONObject jsonObjectInArray = (JSONObject) object;doRenameWork(jsonObjectInArray, jsonObj);}}}}}}
package com.cobra.sankes;import java.io.IOException;import net.sf.json.JSONObject;import net.sf.json.JSONSerializer;public final class JSONNameMappingLoader { public static final String MAPPING_FILE = <span style="font-family: Arial, Helvetica, sans-serif;">"YOUR CONFIGURATION FILE PATH HERE"</span>; private static final JSONObject NAME_MAPPINGS; static { JSONObject jsonObject = null; try { jsonObject = loadNameMappings(); } catch (IOException e) { } NAME_MAPPINGS = jsonObject; } private JSONNameMappingLoader() { super(); } public static JSONObject getNameMappings() { return NAME_MAPPINGS; } private static JSONObject loadNameMappings() throws IOException { String mappingData = ResourcesLoader.readFileByChars(MAPPING_FILE);System.out.println(mappingData); JSONObject jsonData = (JSONObject) JSONSerializer.toJSON(mappingData); return jsonData; }}
package com.cobra.sankes;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.Reader;public final class ResourcesLoader {private ResourcesLoader() {super();} public static String readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; StringBuilder builder = new StringBuilder();; try { reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { if (((char) tempchar) != '\r') { builder.append((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } return builder.toString(); }}
package com.cobra.sankes;public final class Consts {
<span style="white-space:pre"></span>private Consts(){
<span style="white-space:pre"></span>super();
<span style="white-space:pre"></span>}public static final String INCOMING_KEY = "incomingKey";public static final String OUTGOING_KEY = "outgoingKey";public static final String NEED_REMOVAL = "needRemoval";public static final String SUB_JSON_OBJECT = "children";}
And the configuration file should looks like this:
{"children": [{"incomingKey": "original name","needRemoval": false,"outgoingKey": "final name"},{"incomingKey": "original name","children": [{"incomingKey": "original name","needRemoval": true,"outgoingKey": "final name"},{"incomingKey": "original name","outgoingKey": "final name","children": [{"incomingKey": "original name","needRemoval": false,"outgoingKey": "final name"}]}]}]}Here if "outgoingKey" is omitted, means this field name will not be renamed, it was just be used as a path to find it's sub set.
if "needRemoval" is omitted, means this field will not be removed. You can not define it if you want to keep the field because this field's default value is false in the code above.
Here is one simple example of it.
Input here:
{"testing" : "a json string","sample" : "do it","widget" : {"debug" : "on","window" : [{"title": "array1","name": "main_window","width": 500,"height": 500},{"title": "array2","name": "main_window","width": 500,"height": 500}],"image" : {"src": "Images/Sun.png","name": "sun1","hOffset": 250,"vOffset": 250,"alignment": "center"},"text": {"data": "Click Here","size": 36,"style": "bold","name": "text1","hOffset": 250,"vOffset": 100,"alignment": "center","onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"}}}
Configuration file here:
{"children": [{"incomingKey": "sample","needRemoval": false,"outgoingKey": "This is a sample"},{"incomingKey": "widget","children": [{"incomingKey": "debug","needRemoval": false,"outgoingKey": "debug is bit of pain"},{"incomingKey": "image","needRemoval": true},{"incomingKey": "window","needRemoval": false,"children": [{"incomingKey": "title","needRemoval": false,"outgoingKey": "TITLE",},{"incomingKey": "name","needRemoval": false,"outgoingKey": "NAME"}]},{"incomingKey": "text","outgoingKey": "what? I am not a text!","children": [{"incomingKey": "size","needRemoval": false,"outgoingKey": "Which size do you like the most? C, C#, C++?"}]}]}]}This is aiming at to delete "image" object, and to rename "sample", "debug", "text", "text/size", "window/title"
{"testing": "a json string","widget": {"window": [{"width": 500,"height": 500,"TITLE": "array1","NAME": "main_window"},{"width": 500,"height": 500,"TITLE": "array2","NAME": "main_window"}],"debug is bit of pain": "on","what? I am not a text!": {"data": "Click Here","style": "bold","name": "text1","hOffset": 250,"vOffset": 100,"alignment": "center","onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;","Which size do you like the most? C, C#, C++?": 36}},"This is a sample": "do it"}
- A Generic method to modify the names in a JSONObject
- How to Modify the Virtual Memory in a Mac
- a method to set the title of webpart in code
- cannot assign to 'self' outside of a method in the init family
- Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init family
- Cannot assign to 'self' outside of a method in the init family
- Cannot assign to 'self' outside of a method in the init family
- [IOS] 错误:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init
- [ios]关于error:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to 'self' outside of a method in the init family
- 关于error:Cannot assign to \'self\' outside of a method in the init family
- Cannot assign to 'self' outside of a method in the init family
- Cannot assign to 'self' outside of a method in the init family
- iOS中UIScrollView和UIPageControl的使用
- python中range函数和xrange函数的区别
- Junit4单元测试(2)
- unity3d 异步加载关卡进度条显示
- hadoop环境搭建
- A Generic method to modify the names in a JSONObject
- 平面向量加法(10)
- UITableView常用函数
- 查找整数
- UVA 11624 Fire!(kuangbin带你飞 专题一:简单搜索)
- 多重背包问题
- POJ 1952 LITTLE SHOP OF FLOWERS(DP动归,最长递减子序列)
- android屏幕分辨率及自动匹配相关
- 获取沙盒目录