Search code examples
javaandroidjsonstringgson

how to convert the string to JSON?


private IBeaconListener createIBeaconListener() {
        return new SimpleIBeaconListener() {
            @Override
            public void onIBeaconDiscovered(IBeaconDevice ibeacon, IBeaconRegion region) {
                Gson gson = new Gson();
                String json = gson.toJson(ibeacon);

                Gson gson2 = new Gson();
                String deviceId = "{deviceId : 67814f71b5bdb4d3}";
                String json2 = gson2.toJson(obj);

                Log.i("Beacon", "IBeacon discovered: " + json);
                Log.i("Gateway", "Gateway discovered: " + json2);

                new Handler().postDelayed(new Runnable(){
                    @Override
                    public void run() {
                        publish(json + json2);
                    }
                }, 5000);
            }
        };
    }

I want to convert deviceId to JSON Object so that I can publish it together with json. Does anyone know how to do it? This is the result I got:

{"address":"05:B2:68:5B:BC:92","batteryPower":-1,"distance":2.0765944282461007E9,"firmwareVersion":"-1","hashCodeBuilder":{"iConstant":37,"iTotal":17},"major":1,"minor":0,"proximity":"FAR","proximityUUID":"2686f39c-bada-4658-854a-a62e7e5e8b8d","rssi":-94,"shuffled":false,"timestamp":1680527328760,"txPower":11}"{deviceId : 67814f71b5bdb4d3}"

However, I want the output to be like this:

{"address":"05:B2:68:5B:BC:92","batteryPower":-1,"distance":2.0765944282461007E9,"firmwareVersion":"-1","hashCodeBuilder":{"iConstant":37,"iTotal":17},"major":1,"minor":0,"proximity":"FAR","proximityUUID":"2686f39c-bada-4658-854a-a62e7e5e8b8d","rssi":-94,"shuffled":false,"timestamp":1680527328760,"txPower":11,"deviceId":"67814f71b5bdb4d3"}

Solution

  • I created a Gateway class object and used gson on it. The following code example worked for me:

    public class Gateway {
        private String deviceId;
    
        public Gateway(String deviceId) {
            this.deviceId = deviceId;
        }
    
        public String getDeviceId() { return deviceId; }
    
        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }
    }
    
    Gateway gateway = new Gateway("67814f71b5bdb4d3");
    Gson gson2 = new Gson();
    String json2 = gson2.toJson(gateway);