如何从Java中的json对象替换“ emailRecipients”键值

时间:2019-07-05 06:33:33

标签: java json

我需要将emailRecipients的值替换为其他值。

这是JSON

{"payload": {"injectedDetails": "{\"injectedDetails\":\"test\"}","originalPayload": "{\"messageId\":\"232342",
\"emailRecipients\":[\"test@abc.com\"]}"},
    "status": "OK"
}

我在下面尝试过,但是它放置了一个新密钥而不是替换现有密钥。甚至尝试使用putOnce()

jsonObjOriInj=new JSONObject(jsonobjectString);
jsonObjOriInj.put("emailRecipients", "2323");

1 个答案:

答案 0 :(得分:0)

您的JSON无效,但假设JSON应该采用以下格式,

{
    "payload": {
        "injectedDetails": {
             "injectedDetails": "test"
        }
     },
     "originalPayload": {
        "messageId": "232342",
        "emailRecipients":[
            "test@abc.com"
        ]
     },
    "status": "OK"
}
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Main {

    public static void main(String[] args) throws ParseException {

        String data = "{\"payload\":{\"injectedDetails\":{\"injectedDetails\":\"test\"}},\"originalPayload\":{\"messageId\":\"232342\",\"emailRecipients\":[\"test@abc.com\"]},\"status\":\"OK\"}";

        JSONParser parser = new JSONParser();

        JSONObject jsonObject = (JSONObject) parser.parse(data);

        //get originalPayload object
        JSONObject originalPayload = (JSONObject) jsonObject.get("originalPayload");

        // create new json array
        JSONArray newEmailRecipients = new JSONArray();

        // add new email recipients
        newEmailRecipients.add("updated_test@abc.com");

        // update originalPayload object with new emailRecipients
        originalPayload.put("emailRecipients", newEmailRecipients);

        // update JSON with updates originalPayload object
        jsonObject.put("originalPayload", originalPayload);

        System.out.println(jsonObject);

    }

}

输出:

{"payload":{"injectedDetails":{"injectedDetails":"test"}},"originalPayload":{"messageId":"232342","emailRecipients":"[updated_test@abc.com]"},"status":"OK"}