如何将字符串转换为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);
}
};
}

我想将deviceId转换为JSON对象,以便我可以与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"}

我创建了一个Gateway类对象,并在其上使用gson。下面的代码示例为我工作:

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);

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

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);

最新更新