0
String str = "{"id":"4ebd7e4f","start_page_ui_id":"","business_unit":["5b65aced"],"props":{"metadata":"[]","postsPerPage":"20","network_id":"1b375ffd"},"render_engine":"twig"}"

Here I want to replace "metadata":"[]" to "metadata":"["key":"value,value1","key1":"value2"]"

for this i tried to replace as

str =str.replace("\"metadata\":\"[\"", "\"metadata\": \"[{\"key\":\"key\",\"val\":\"value,value1\"},{\"key\":\"key1\",\"val\":\"value2\"}");

But it is not getting replaced. I don't understand why?? Can any one please help me to solve this issue.

I want to replace another string "postsPerPage":"20" to "postsPerPage":"6"

for this i tried with

str = str .replace("\"postsPerPage\": \"20\",", "\"postsPerPage\": \"9\",");

Here also the value is not changing.

6
  • 4
    why are you not using json classes to this? Commented Jun 19, 2018 at 7:21
  • 1
    What is your json parser , what library ? Commented Jun 19, 2018 at 7:23
  • Check this. You can then reassign values in your Java object, before converting it back to JSON with your desired output. Commented Jun 19, 2018 at 7:30
  • The content was in a Json format. I have used toString() method to convert into string. After converting it into string I was trying to replace. Commented Jun 19, 2018 at 7:35
  • That is not a long term solution and is bound to get unwieldy in the near future and is also known as a shortcut! Lol its your choice how you do it, but maintainable and understandable is the better way out! Commented Jun 19, 2018 at 7:37

5 Answers 5

1

Use a JSON third-party lib for this, GSON or Jackson being the most popular ones.

For example with GSON (only for small samples! for large blobs of JSON you should consider using the stream API):

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Main {

    public static void main(String[] args) {
        Gson gson = new Gson();
        String str = "{\"id\":\"4ebd7e4f\",\"start_page_ui_id\":\"\",\"business_unit\":[\"5b65aced\"],\"props\":{\"metadata\":\"[]\",\"postsPerPage\":\"20\",\"network_id\":\"1b375ffd\"},\"render_engine\":\"twig\"}";
        String metadataReplacementJson = "[{\"key\":\"key\",\"val\":\"value,value1\"},{\"key\":\"key1\",\"val\":\"value2\"}]";
        JsonObject jsonObject = gson.fromJson(str, JsonObject.class);

        jsonObject
                .get("props")
                .getAsJsonObject()
                .remove("metadata");

        jsonObject
                .get("props")
                .getAsJsonObject()
                .add("metadata", gson.fromJson(metadataReplacementJson, JsonArray.class));

        System.out.println(gson.toJson(jsonObject));
    }
}

Console output:

{"id":"4ebd7e4f","start_page_ui_id":"","business_unit":["5b65aced"],"props":{"metadata":[{"key":"key","val":"value,value1"},{"key":"key1","val":"value2"}],"postsPerPage":"20","network_id":"1b375ffd"},"render_engine":"twig"}
Sign up to request clarification or add additional context in comments.

2 Comments

What is the error you're getting? Anyway you might try removing the property first - see the updated answer
Also what GSON version are you using?
0

Rather a lengthy process, I will outline here what you need to do inorder to manuplate your JSON.

  • Create a POJO for your JSON.
  • Parse your JSON and create a POJO Object.
  • Now manipulate the POJO Object with your new data (Update values, replace etc..)
  • Write back the fresh JSON.

Libraries: GSON, Jackson are of help here. You can also use online JSON to POJO converters to make your task even more easier.

2 Comments

The POJO is not strictly necessary, you can use the JSON tree objects returned by your JSON library directly. But yes, definitely use a JSON parser, don't work on Strings.
@Thilo Yes I agree, GSON and Jackson being the best ones so far.
0

You have to replace with

"\"metadata\":\"[" 

not

"\"metadata\":\"[\""

and

"\"postsPerPage\": \"20\","

should be

"\"postsPerPage\":\"20\""

Comments

0

String objects are immutable, so whenever we perform any operation in existing string object at that time a new string object is created.The new Stirng object is not assign to any any String object.

so str = str .replace("\"postsPerPage\": \"20\",", "\"postsPerPage\": \"9\",");

In above line created new object it is automatically eligible for garbage collection.

String str2 = str .replace("\"postsPerPage\": \"20\",", "\"postsPerPage\": \"9\",");

here new String object created. str2 is point to String object.

now you can use str2 will work.

Comments

0

For those who are still interested, java 21 has introduced an STR Template

STR."Invalid order quantity : \{qty}";

enter image description here

Comments

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.