android 如何将字符串转换为JSON?

6ioyuze2  于 2023-04-04  发布在  Android
关注(0)|答案(2)|浏览(451)
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);
            }
        };
    }

我想把 deviceId 转换成JSON Object,这样我就可以和 json 一起发布了。有人知道怎么做吗?这是我得到的结果:

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

但是,我希望输出是这样的:

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

31moq8wy1#

要将deviceId字符串转换为JSON object,可以使用com.google.gson package中的JsonObject类。下面是一个示例:

Gson gson = new Gson();

// create a new JSON object for the payload
JsonObject payload = new JsonObject();

// convert the ibeacon object to a JSON element and add it to the payload
payload.add("ibeacon", gson.toJsonTree(ibeacon));

// create a new JSON object for the deviceId
JsonObject deviceId = new JsonObject();
deviceId.addProperty("deviceId", "67814f71b5bdb4d3");

// add the deviceId object to the payload
payload.add("deviceId", deviceId);

// convert the payload to a JSON string
String json = gson.toJson(payload);

// publish the JSON string
publish(json);

现在您可以在publish方法中使用json2变量来发布ibeacon和deviceId信息。

xv8emn3q

xv8emn3q2#

代码对我来说不是很清楚,但你可以尝试这样的东西

String json = gson.toJson(ibeacon);

   JSONObject jsonObj = new JSONObject(json );

    try {
        jsonObj.put("deviceId", "67814f71b5bdb4d3");
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    String myJSON = JSON.stringify(jsonObj);

相关问题