如何使用JAVA将Properties类转换为JSON对象

时间:2016-09-07 11:59:01

标签: java json properties

任何人都可以帮助我吗?如何将以下输入转换为JSON对象?

输入:

{ "details": { "device/0/endPointClientName": "ndm-xx-1", "device/1/endPointClientName": "ndm-xx-2", "EnergyMeter/0/current": "20", "EnergyMeter/0/total": "400", } }

输出: -

{  "device": [ {"endPointClientName":"ndm-xx-1" }, {"endPointClientName":"ndm-xx-2" } ], "EnergyMeter": [ {"current":"20", "total":"400"} ] } 

我将Input作为带有Properties类的JSON对象。在输入中,我们正在共享FULL PATH。我们必须将其转换为JSON对象。

1 个答案:

答案 0 :(得分:-1)

[演示] https://jsfiddle.net/CntChen/vh7kat5a/

   var input = {
      "details": {
        "device/0/endPointClientName": "ndm-xx-1",
        "device/1/endPointClientName": "ndm-xx-2",
        "EnergyMeter/0/current": "20",
        "EnergyMeter/0/total": "400",
      }
    };

    function decodeFlatObj(flatOjb) {
      var outputObj = {};
      for (var key in flatOjb) {
        var objNow = outputObj;
        var subkey = key.split('/');

        for (var i = 0; i < subkey.length - 1; i++) {
          // next subkey is number
          if (/\d|[1-9]\d*/.test(subkey[i + 1])) {
            // current subkey is number
            if (/\d|[1-9]\d*/.test(subkey[i])) {
              objNow.push([]);
              objNow = objNow[parseInt(subkey[i])];
            } else {
              objNow[subkey[i]] = objNow[subkey[i]] || [];
              objNow = objNow[subkey[i]];
            }
          } else { // next subkey is object
            // current subkey is number
            if (/\d|[1-9]\d*/.test(subkey[i])) {
              objNow[parseInt(subkey[i])] = objNow[parseInt(subkey[i])] || {};
              objNow = objNow[parseInt(subkey[i])];
            } else {
              objNow[subkey[i]] = objNow[subkey[i]] || {};
              objNow = objNow[subkey[i]];
            }
          }
        }

        var valueDecode;
        if (typeof flatOjb[key] === 'object') {
          valueDecode = decodeFlatObj(flatOjb[key]);
        } else {
          valueDecode = flatOjb[key];
        }

        if (/\d|[1-9]\d*/.test(subkey[subkey.length - 1])) {
          objNow[parseInt(subkey[subkey.length - 1])].push(valueDecode);
        } else {
          objNow[subkey[subkey.length - 1]] = valueDecode;
        }
      }

      return outputObj;
    }

    var output = decodeFlatObj(input);
    console.log(input);
    console.log(JSON.stringify(output));
    //{"details":{"device":[{"endPointClientName":"ndm-xx-1"},{"endPointClientName":"ndm-xx-2"}],"EnergyMeter":[{"current":"20","total":"400"}]}}