本文讲解如何使用 gson 将独立的字符串字段(如 deviceid)正确嵌入已序列化的 json 对象,避免拼接导致的格式错误,实现结构完整、合法的 json 合并输出。
本文讲解如何使用 gson 将独立的字符串字段(如 deviceid)正确嵌入已序列化的 json 对象,避免拼接导致的格式错误,实现结构完整、合法的 json 合并输出。
在 Android 或 Java 开发中,常需将设备扫描数据(如 iBeacon)与网关元信息(如 deviceId)一并序列化为统一 JSON 发送至服务端。但直接字符串拼接(如 json + json2)会破坏 JSON 结构——正如示例中产生的非法双 JSON 对象(一个对象 + 一个字符串字面量),导致解析失败。
根本问题在于: "{deviceId : 67814f71b5bdb4d3}" 是手动拼写的字符串,不是合法 JSON 对象;而 gson.toJson(ibeacon) 输出的是标准 JSON 对象。二者简单相加得到的是无效 JSON(两个顶层值并列),而非单个融合对象。
✅ 正确做法是 统一建模 + 一次序列化。推荐创建组合数据类,将 IBeaconDevice 与 Gateway 属性封装为同一 POJO:
public class BeaconReport {
private String address;
private int batteryPower;
private double distance;
private String firmwareVersion;
private int major;
private int minor;
private String proximity;
private String proximityUUID;
private int rssi;
private boolean shuffled;
private long timestamp;
private int txPower;
private String deviceId; // 新增字段
// 构造函数(可选)或通过 Builder/GsonBuilder 注入
public BeaconReport(IBeaconDevice ibeacon, String deviceId) {
// 手动赋值关键字段(或使用反射/工具类简化)
this.address = ibeacon.getAddress();
this.batteryPower = ibeacon.getBatteryPower();
this.distance = ibeacon.getDistance();
this.firmwareVersion = ibeacon.getFirmwareVersion();
this.major = ibeacon.getMajor();
this.minor = ibeacon.getMinor();
this.proximity = ibeacon.getProximity().toString();
this.proximityUUID = ibeacon.getProximityUUID();
this.rssi = ibeacon.getRssi();
this.shuffled = ibeacon.isShuffled();
this.timestamp = ibeacon.getTimestamp();
this.txPower = ibeacon.getTxPower();
this.deviceId = deviceId;
}
// getter 方法(省略,按需生成)
}然后在监听器中使用:
@Override
public void onIBeaconDiscovered(IBeaconDevice ibeacon, IBeaconRegion region) {
String deviceId = "67814f71b5bdb4d3";
BeaconReport report = new BeaconReport(ibeacon, deviceId);
Gson gson = new Gson();
String finalJson = gson.toJson(report); // ✅ 单次生成合法 JSON
Log.i("Beacon", "Full report: " + finalJson);
new Handler().postDelayed(() -> publish(finalJson), 5000);
}⚠️ 注意事项:
- 避免对 ibeacon 对象直接调用 gson.toJson() 后再拼接字符串——这本质是反模式;
- 若 IBeaconDevice 包含不可序列化字段(如 hashCodeBuilder),建议用 @Expose 注解或 GsonBuilder.excludeFieldsWithoutExposeAnnotation() 过滤;
- 如需动态扩展字段(不修改类),可使用 JsonObject 手动构建:
JsonObject jsonObject = JsonParser.parseString(gson.toJson(ibeacon)).getAsJsonObject();
jsonObject.addProperty("deviceId", "67814f71b5bdb4d3");
String finalJson = jsonObject.toString(); // ✅ 安全合并总结:JSON 合并 ≠ 字符串拼接。始终优先通过面向对象建模或 JsonObject API 维护结构完整性,确保输出符合 RFC 8259 标准,为前后端协作奠定可靠基础。


















