Gson实现:修改json字符串中某个key对应的value值、如何修改json字符串中某个key

该文章提供两个Java方法,分别用于修改JSON字符串中某个key和对应的value。方法使用递归遍历JSON对象和数组,实现键的替换以及值的更新。在测试部分,展示了如何使用这些方法改变示例JSON数据。
摘要由CSDN通过智能技术生成

修改json字符串中某个key

public static JsonElement replaceKey(JsonElement source, Map<String, String> rep) {
    if (source == null || source.isJsonNull()) {
        return JsonNull.INSTANCE;
    }
    if (source.isJsonPrimitive()) {
        return source;
    }
    if (source.isJsonArray()) {
        JsonArray jsonArr = source.getAsJsonArray();
        JsonArray jsonArray = new JsonArray();
        jsonArr.forEach(item -> {
            jsonArray.add(replaceKey(item, rep));
        });
        return jsonArray;
    }
    if (source.isJsonObject()) {
        JsonObject jsonObj = source.getAsJsonObject();
        Iterator<Entry<String, JsonElement>> iterator = jsonObj.entrySet().iterator();
        JsonObject newJsonObj = new JsonObject();
        iterator.forEachRemaining(item -> {
            String key = item.getKey();
            JsonElement value = item.getValue();
            if (rep.containsKey(key)) {
                String newKey = rep.get(key);
                key = newKey;
            }
            newJsonObj.add(key, replaceKey(value, rep));
        });

        return newJsonObj;
    }
    return JsonNull.INSTANCE;
}

修改json字符串中某个key对应的value值

public static JsonElement replaceJsonNode(JsonElement jsonElement, Map<String, Object> map) {

    if (map.size() == 0) {
        return jsonElement;
    }

    // 判断如果是简单json串直接返回
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement;
    }

    // 判断如果是数组类型字符串,则逐个解析
    if (jsonElement.isJsonArray()) {
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        JsonArray jsonArryNew = new JsonArray();
        for (JsonElement element : jsonArray) {
            // 递归调用
            jsonArryNew.add(replaceJsonNode(element, map));
        }
        return jsonArryNew;
    }

    // 判断如果是key-value类型的
    if (jsonElement.isJsonObject()) {
        JsonObject object = jsonElement.getAsJsonObject();
        JsonObject objectNew = new JsonObject();
        for (String key : object.keySet()) {
            // 如果和目标字段匹配则更换value;
            if (map.containsKey(key)) {
                Object newValue = map.get(key);
                if (newValue instanceof String) {
                    object.addProperty(key, (String) newValue);
                } else if (newValue instanceof Boolean) {
                    object.addProperty(key, (Boolean) newValue);
                } else if (newValue instanceof Character) {
                    object.addProperty(key, (Character) newValue);
                } else {
                    object.addProperty(key, (Number) newValue);
                }
            }
            JsonElement jsonEle = object.get(key);
            JsonElement jsonElementNew = replaceJsonNode(jsonEle, map);
            objectNew.add(key, jsonElementNew);
        }
        return objectNew;
    }
    return jsonElement;
}

测试

public static void main(String[] args) {
    String json = "{\"order_sn\":\"14031000273822\",\"carriers_code\":1100000357,\"carrier\":\"浙江派尔快递\",\"package_type\":2,\"packages\":[{\"0\":{\"good_sn\":\"ALM2236W36\",\"amount\":\"2\"},\"1\":{\"good_sn\":\"ALM2236W37\",\"amount\":\"2\"},\"transport_no\":\"test5715A\"},{\"0\":{\"good_sn\":\"ALM2236W35\",\"amount\":\"2\"},\"transport_no\":\"test5715B\"}]}";
    JsonElement jsonEle = new JsonParser().parse(json);
    HashMap<String, String> rep = new HashMap<>();
    rep.put("order_sn", "order_id");
    rep.put("carriers_code", "carrier_code");
    rep.put("good_sn", "barcode");
    JsonElement replaceKey = replaceKey(jsonEle, rep);
    System.out.println(replaceKey.toString());

    Map<String, Object> map = new HashMap();
    map.put("order_sn","00000000");
    map.put("carriers_code","9999999");
    map.put("good_sn",888);
    System.out.println(replaceJsonNode(jsonEle, map).toString());
}

结果

  1. 运行前
    {
        "order_sn": "14031000273822",
        "carriers_code": 1100000357,
        "carrier": "浙江派尔快递",
        "package_type": 2,
        "packages": [
            {
                "0": {
                    "good_sn": "ALM2236W36",
                    "amount": "2"
                },
                "1": {
                    "good_sn": "ALM2236W37",
                    "amount": "2"
                },
                "transport_no": "test5715A"
            },
            {
                "0": {
                    "good_sn": "ALM2236W35",
                    "amount": "2"
                },
                "transport_no": "test5715B"
            }
        ]
    }
    
  2. 运行后
    • 修改key
      {
          "order_id": "14031000273822",
          "carrier_code": 1100000357,
          "carrier": "浙江派尔快递",
          "package_type": 2,
          "packages": [
              {
                  "0": {
                      "barcode": "ALM2236W36",
                      "amount": "2"
                  },
                  "1": {
                      "barcode": "ALM2236W37",
                      "amount": "2"
                  },
                  "transport_no": "test5715A"
              },
              {
                  "0": {
                      "barcode": "ALM2236W35",
                      "amount": "2"
                  },
                  "transport_no": "test5715B"
              }
          ]
      }
      
    • 修改对应key的value
      {
          "order_sn": "00000000",
          "carriers_code": "9999999",
          "carrier": "浙江派尔快递",
          "package_type": 2,
          "packages": [
              {
                  "0": {
                      "good_sn": 888,
                      "amount": "2"
                  },
                  "1": {
                      "good_sn": 888,
                      "amount": "2"
                  },
                  "transport_no": "test5715A"
              },
              {
                  "0": {
                      "good_sn": 888,
                      "amount": "2"
                  },
                  "transport_no": "test5715B"
              }
          ]
      }
      
假设有以下json字符串: ``` { "name": "张三", "age": 20, "gender": "男", "hobbies": ["篮球", "游泳", "旅游"], "address": { "province": "广东", "city": "深圳", "district": "南山区" } } ``` 可以使用Gson库将其解析为对应Json对象,并根据key获取value。 首先需要添加Gson库的依赖: ``` dependencies { implementation 'com.google.code.gson:gson:2.8.5' } ``` 然后可以编写以下代码: ```java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GsonTest { public static void main(String[] args) { String jsonStr = "{\"name\":\"张三\",\"age\":20,\"gender\":\"男\",\"hobbies\":[\"篮球\",\"游泳\",\"旅游\"],\"address\":{\"province\":\"广东\",\"city\":\"深圳\",\"district\":\"南山区\"}}"; Gson gson = new Gson(); JsonElement jsonElement = gson.fromJson(jsonStr, JsonElement.class); if (jsonElement != null && jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); String name = jsonObject.get("name").getAsString(); int age = jsonObject.get("age").getAsInt(); String gender = jsonObject.get("gender").getAsString(); System.out.println("姓名:" + name); System.out.println("年龄:" + age); System.out.println("性别:" + gender); JsonElement hobbiesElement = jsonObject.get("hobbies"); if (hobbiesElement != null && hobbiesElement.isJsonArray()) { System.out.print("爱好:"); for (JsonElement hobby : hobbiesElement.getAsJsonArray()) { System.out.print(hobby.getAsString() + " "); } System.out.println(); } JsonObject addressObject = jsonObject.getAsJsonObject("address"); if (addressObject != null) { String province = addressObject.get("province").getAsString(); String city = addressObject.get("city").getAsString(); String district = addressObject.get("district").getAsString(); System.out.println("省份:" + province); System.out.println("城市:" + city); System.out.println("区县:" + district); } } } } ``` 输出结果为: ``` 姓名:张三 年龄:20 性别:男 爱好:篮球 游泳 旅游 省份:广东 城市:深圳 区县:南山区 ``` 可以看到,通过Gson库解析后可以方便地获取Json对象的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

?abc!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值