You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端如何使用GSON将JSON数组字符串插入到另一个JSON对象中

GSON合并两个JSON字符串的实现方法

你提供的第二个JSON存在格式疏漏,缺少开头的{,修正后的合法格式为:

{"surveys":[{"UId":"2","occupier": "rent","propertyId": "3","formId":1605250886166,"isSubmitted":false,"id":1}]}

具体实现步骤如下:

  • 第一步:集成GSON依赖(已集成可跳过),Maven配置参考:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
  • 第二步:编写处理代码,示例如下:
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonMergeTest {
    public static void main(String[] args) {
        // 定义两个原始JSON字符串
        String floorJson = "{\"floors\":[{\"coveredArea\":\"200\",\"floorId\":\"12\",\"uploaded\":false,\"id\":1},{\"coveredArea\":\"200\",\"floorId\":\"12\",\"uploaded\":false,\"id\":5}]}";
        String surveyJson = "{\"surveys\":[{\"UId\":\"2\",\"occupier\": \"rent\",\"propertyId\": \"3\",\"formId\":1605250886166,\"isSubmitted\":false,\"id\":1}]}";

        Gson gson = new Gson();

        // 处理楼层JSON,过滤不需要的字段,提取有效内容
        JsonObject floorRoot = JsonParser.parseString(floorJson).getAsJsonObject();
        JsonArray originFloors = floorRoot.getAsJsonArray("floors");
        JsonArray processedFloors = new JsonArray();
        for (int i = 0; i < originFloors.size(); i++) {
            JsonObject originFloor = originFloors.get(i).getAsJsonObject();
            JsonObject floorItem = new JsonObject();
            floorItem.addProperty("floorId", originFloor.get("floorId").getAsString());
            floorItem.addProperty("coveredArea", originFloor.get("coveredArea").getAsString());
            processedFloors.add(floorItem);
        }

        // 处理调研JSON,修改目标字段并插入楼层数组
        JsonObject surveyRoot = JsonParser.parseString(surveyJson).getAsJsonObject();
        JsonObject targetSurvey = surveyRoot.getAsJsonArray("surveys").get(0).getAsJsonObject();
        // 按需求修改字段值
        targetSurvey.addProperty("UId", "161");
        targetSurvey.addProperty("isSubmitted", true);
        // 移除不需要的冗余字段
        targetSurvey.remove("id");
        // 插入处理好的楼层数组
        targetSurvey.add("floor", processedFloors);

        // 格式化输出最终结果
        String result = gson.newBuilder().setPrettyPrinting().create().toJson(surveyRoot);
        System.out.println(result);
    }
}
  • 第三步:运行代码即可得到和你期望格式完全一致的输出结果。

内容的提问来源于stack exchange,提问作者Umer Mir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 23:54:03