【问题标题】:setting the value in json array based on checking some condition根据检查某些条件在 json 数组中设置值
【发布时间】:2022-01-18 09:57:12
【问题描述】:

我有这个方法pay.getPaymentDetails(),它的返回类型是字符串,它返回下面的字符串

[
    {
        "mcTtid": 201657083281,
        "cardLast4Digits": "0887",
        "paymentType": "CREDIT CARD",
        "originalPaymentCategory": {
            "code": "Q",
            "name": "CREDIT CARD"
        }
    },
    {
        "veTtid": 21656148003,
        "cardLast4Digits": "4777",
        "paymentType": "GIFT CARD",
        "originalPaymentCategory": {
            "code": "Q",
            "name": "GIFT CARD"
        }
    },
    {
        "mcTtid": 201625819,
        "cardLast4Digits": "8388",
        "paymentType": "GIFT CARD",
        "originalPaymentCategory": {
            "code": "w",
            "name": "GIFT CARD"
        }
    }
]

现在我用下面的代码提取了属性 paymentType 的值

String paymentTypeValue = null;
try {
    JSONArray jsonArr = new JSONArray(FormatUtil.gcpBlobAsString(pay.getPaymentDetails()));
    for (int i = 0; i < jsonArr.length(); i++) {
        paymentTypeValue = jsonArr.getJSONObject(i).getString("paymentType");
    }
}
catch (JSONException e) {
    logger.error("Json exception-->" + e.getMessage());
    throw new JsonException(e);
}

现在我的查询是我需要检查 value 属性 paymentType 是否为 GIFT CARD 那么我需要将其设置为 CREDIT CARD 所以请告知我该如何设置它

if (paymentTypeValue.equalsIgnoreCase("GIFT CARD")) {
    ...
}

【问题讨论】:

    标签: java java-8


    【解决方案1】:

    使用.put(fieldName, newValue) 方法。它替换或添加已经存在的字段。

    这是一个例子:

    String paymentTypeValue = null;
    try {
        JSONArray jsonArr = new JSONArray(FormatUtil.gcpBlobAsString(pay.getPaymentDetails()));
        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject currentObject = jsonArr.getJSONObject(i);
            paymentTypeValue = currentObject.getString("paymentType");
            
            if (paymentTypeValue.equalsIgnoreCase("GIFT CARD")) {
                currentObject.put("paymentType", "CREDIT CARD"); // <------------- This does what you need
            }
        }
        
        // Get your JSON array and turn it into a string or whatever you need
    }
    catch (JSONException e) {
        logger.error("Json exception-->" + e.getMessage());
        throw new JsonException(e);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2016-02-15
      • 2012-03-08
      相关资源
      最近更新 更多