在Java中如何添加嵌套的地图对象

时间:2019-12-17 21:20:34

标签: java hashmap

我有一个JSON数据,并将该有效负载转换为嵌套的地图对象。但是根据我的逻辑,它是最重要的。

我正在输入这样的json

{"mapping": {
        "EVENT.alertMessage": "input.Message",
        "EVENT.id": "input.id",
        "EVENT.severity": "Functions.toString(\"P1\")",
        "EVENT.eventTime": "input.eventTime",
        "EVENT.eventType": "input.alertType",
        "EVENT.geocoordinates.location": "Functions.toString(\"\")",
        "EVENT.deviceName": "Functions.toString(\"\")",
        "EVENT.visualInfo.imageUrl": "input.imageUrl",
        "EVENT.deviceId": "input.cameraId",
        "EVENT.geocoordinates.longitude": "Functions.toString(\"\")",
        "EVENT.visualInfo.videoUrl": "input.videoUrl",
        "EVENT.tenantCode": "Functions.toString(\"\")",
        "EVENT.MAC": "input.cameraId",
        "EVENT.DATE_TIME": "Functions.currentDate(\"yyyy-MM-dd HH:mm:ss\",\"UTC\")",
        "EVENT.geocoordinates.latitude": "Functions.toString(\"\")"
    }
    }

在上面输入的JSON键中,我正在迭代并形成地图对象。

外汇: 输入:

{"mapping": {
            "TEST.key1": "a",
            "TEST.key2.key3": "b",
           }
}
OUTPUT:
{
"TEST":{
  "key1":a,
  "key2":{
   "key3":b
   }
  }
 }

我写的代码是

JSONObject json=new JSONObject(mappingData).getJSONObject("mapping");
            Iterator<String> keys=new JSONObject(mappingData).getJSONObject("mapping").keys();
            Map<String,Object> map = new HashMap<>();
            while(keys.hasNext()) {
                String val = keys.next();
                String[] key=val.split("(?<!/)\\.");
                Map<String, Object> lastKeyMap = null;
                for(int i=0;i<key.length;i++)
                {

                    if(i== 0 && key.length==1){

                        String outputVal=json.getString(val);
                        if(outputVal.contains("[]")){
                            outputVal=outputVal.replace("[]", "[i]");
                        }
                        //Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])|([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])")
                        //      .matcher(outputVal);
                        Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9]{0,})")
                                        .matcher(outputVal);
                        while (m.find()) {
                            outputVal=m.replaceAll("[`$1`]").replace("/", "");
                        }

                        if(key[i].contains("/"))
                        {
                            map.put("`"+key[i].replace("/", "")+"`",outputVal);
                        }
                        else{
                            map.put(key[i],outputVal);
                        }
                    }


                    else if(i== 0 && key.length>1){

                        if(map.containsKey(key[i])){
                            lastKeyMap = (Map<String, Object>) map.get(key[i]);
                        }else{
                            if(key[i].contains("/"))
                            {
                                lastKeyMap = new HashMap<String,Object>();
                                map.put("`"+key[i].replace("/", "")+"`",lastKeyMap);
                            }
                            else{
                                lastKeyMap = new HashMap<String,Object>();
                                map.put(key[i],lastKeyMap);
                            }
                        }

                    }else if(i== key.length-1 ){

                        String outputVal=json.getString(val);
                        if(outputVal.contains("[]")){
                            outputVal=outputVal.replace("[]", "[i]");
                        }
                        //Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])|([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9])")
                        //      .matcher(outputVal);
                        Matcher m = Pattern.compile("\\.([a-zA-Z0-9]{0,}\\/.[a-zA-Z0-9]{0,})")
                                        .matcher(outputVal);
                        while (m.find()) {
                            outputVal=m.replaceAll("[`$1`]").replace("/", "");
                        }

                        if(key[i].contains("/"))
                        {
                            lastKeyMap.put("`"+key[i].replace("/", "")+"`", outputVal);
                        }
                        else{
                            lastKeyMap.put(key[i], outputVal);
                        }
                    }else{
                        Map<String,Object> objMap = new HashMap<>();
                        if(key[i].contains("/"))
                        {
                            lastKeyMap.put("`"+key[i].replace("/", "")+"`", objMap);
                            lastKeyMap = objMap;
                        }
                        else{
                            lastKeyMap.put(key[i], objMap);
                            lastKeyMap = objMap;
                        }
                    }


                }
            }

我得到的输出是:

{EVENT={severity=Functions.toString("P1"), alertMessage=input.alertMessage, id=input.id, eventTime=input.eventTime, visualInfo={videoUrl=input.videoUrl}, eventType=input.alertType, tenantCode=Functions.toString(""), DATE_TIME=Functions.currentDate("yyyy-MM-dd HH:mm:ss","UTC"), geocoordinates={latitude=Functions.toString("")}, deviceName=Functions.toString(""), deviceId=input.cameraId, MAC=input.cameraId}}

但是由于地图被覆盖,结果EVENT.geocoordinates.longitudeEVENT.geocoordinates.longitude被跳过。像这样的EVENT.visualInfo.imageUrl也被EVENT.visualInfo.videoUrl覆盖。因此,我该如何克服这个问题,并通过迭代而不用覆盖json的形式来形成带有所有json键的map或json。

1 个答案:

答案 0 :(得分:0)

最好的方法是根据json模式创建Java类:

public class Test {

    @SerializedName("mapping")
    public Mapping mapping;

    static public class Mapping {

        @SerializedName("EVENT.alertMessage")
        public String alertMessage;

        @SerializedName("EVENT.id")
        public String id;

        @SerializedName("EVENT.severity")
        public String severity;

        @SerializedName("EVENT.eventTime")
        public String eventTime;

        @SerializedName("EVENT.eventType")
        public String eventType;

        @SerializedName("EVENT.geocoordinates.location")
        public String location;

        @SerializedName("EVENT.deviceName")
        public String deviceName;

        @SerializedName("EVENT.visualInfo.imageUrl")
        public String imageUrl;

        @SerializedName("EVENT.deviceId")
        public String deviceId;

        @SerializedName("EVENT.geocoordinates.longitude")
        public String longitude;

        @SerializedName("EVENT.visualInfo.videoUrl")
        public String videoUrl;

        @SerializedName("EVENT.tenantCode")
        public String tenantCode;

        @SerializedName("EVENT.MAC")
        public String mac;

        @SerializedName("EVENT.DATE_TIME")
        public String dateTime;

        @SerializedName("EVENT.geocoordinates.latitude")
        public String latitude;
    }
}

然后使用Google gson库进行解析

Test test = new Gson().fromJson("jsonString", Test.class);

使用自己的Java对象比使用JSONObject要容易得多

我当前在gradle文件中对gson的依赖性:

implementation("com.google.code.gson:gson:2.8.6")