0
[
    "label": {
        "originalName"      : "Case #",
        "modifiedLabel"     : "Case #",
        "labelId"           : "case_number_lbl",
        "isEditable"        : "true",
        "imageClass"        : ""
    }
]

In the above Json Array I need to replace "Case #" with "Ticket #". This is occuring in somany places. Any one update please. Thanks In advance.

3
  • What is the type of the data? Is it org.json.JSONArray? Commented Nov 17, 2015 at 10:13
  • Yes. My string is JsonObject With JSONArray Commented Nov 17, 2015 at 10:14
  • This is not a valid json. If you have an array [ ... ] the elements inside do not have names. "label": should not be there. Commented Nov 17, 2015 at 12:29

3 Answers 3

2

I think a simple loop should solve your problem:

public static void main(String[] args) throws JSONException {
    JSONArray array = new JSONArray("[" +
            "    {" +
            "        originalName      : \"Case #\"," +
            "        modifiedLabel     : \"Case #\"," +
            "        labelId           : \"case_number_lbl\"," +
            "        isEditable        : \"true\"," +
            "        imageClass        : \"\"" +
            "    }" +
            "]");

    System.out.println(array.toString(2));

    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.getJSONObject(i);
        JSONArray keys = object.names();
        for (int j = 0; j < keys.length(); j++) {
            String key = keys.getString(j);
            if (object.getString(key).equals("Case #")) {
                object.put(key, "Ticket #");
            }
        }
    }

    System.out.println();
    System.out.println(array.toString(2));
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use GSON to convert your json to java Object and then you can change your string .

Comments

1

You can exchange the value with the help String.replaceAll()

String jSONString = ...; // Your JSon string
String newString = jSONString.replace("Case #", "Ticket #");

2 Comments

Can you explain why you prefer to use replaceAll over replace?
Hi Tom, replace is a better match, (I agree). replaceAll uses regex, where replace only uses a CharSequence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.