在检查某些条件的基础上设置json数组中的值



我有一个返回类型为字符串的方法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);
}

现在我的问题是,我需要检查如果值属性paymentType是GIFT CARD,那么我需要将其设置为CREDIT CARD,所以请建议我如何将其设置回

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

使用.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);
}

最新更新