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"


Output here:

{"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"}




0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 被地雷蜂蛰了怎么办 被葫芦蜂蛰了怎么办 嘴巴被蜜蜂蛰了怎么办 被蜜蜂蜇伤了怎么办 婴儿被蜜蜂蜇了怎么办 婴儿被黄蜂蛰了怎么办 蜜蜂在石头缝里怎么办 中蜂蜂王不产卵怎么办 冲电器充电变慢怎么办 摇号审核通过后怎么办 京东白条开不了怎么办 得了病心里压力大怎么办 电视家看直播卡怎么办 日上提货单丢了怎么办 想直飞香港l签怎么办 u盘识别不出来怎么办 卫生间下水道有小飞虫怎么办 橙光一直闪退怎么办 若白回来了,长安怎么办 没了你以后我该怎么办 玩cf的时候闪退怎么办 婴儿嗓子哭哑了怎么办 宝宝嗓子哭哑了怎么办 小孩嗓子哭哑了怎么办 孩子嗓子哭哑了怎么办 月经来了晚上漏怎么办 在学校月经漏了怎么办 月经来了血下不来怎么办 想让月经快点来怎么办 孩子来月经不规律怎么办 一个月来2次月经怎么办 14岁月经不规律怎么办 不是经期内裤有黑色血怎么办 月经量多血块多怎么办 网友见面没上她怎么办 拔完智齿老流血怎么办 学车教练不教怎么办 想开奶茶店没有经验怎么办 宝宝吃多了不消化怎么办 吃了糖精和鸡蛋怎么办 小米平板2太卡了怎么办