0

I am retreiving data from a URL into a String a, and passing this string as an argument to gson's fromJson method. Now I need to replace some of the substrings in string a.

    String url = "abc";
    String a = getDataFromURL(url); //this string contains all the data from the URL, and getDataFromURL is the method that reads the data from the URL.
    String tmp = "\"reservation\":\"www.\"";
    String tmpWithHttp = "\"reservation\":\"http://www.\"";

    if(a.contains(tmp))
    {
    a = a.replace(a, tmpWithHttp);
    }

All the data in the URL is JSON. The requirement I have here is, if the String a contains a substring - "reservation":"www., replace that with "reservation":"http://www.

The above code I have is not working. Could someone please help me here?

3
  • 1
    In addition to Rohit Jain's answer, your code is checking for "reservation":"www.", not "reservation":"www. (as your question specifies). That small difference could cause it to not find the replacement string. Commented Jul 20, 2013 at 19:55
  • @Vulcan: Post it as an answer. I am pretty sure this is the real error here. Commented Jul 20, 2013 at 19:58
  • @Vulcan - You are 100% right. Yup, post it as an answer, and I will accept it :) Commented Jul 20, 2013 at 20:00

2 Answers 2

3

You probably mean:

a = a.replace(tmp, tmpWithHttp);

instead of:

a = a.replace(a, tmpWithHttp);

And you don't need to do a contains() check before replacing. String#replace method will replace only if the substring to replace is present. So, you can remove the surrounding if.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, sorry about that. I didn't paste my code as is. Modified it here in the question ;)
2

In your question, you specify that you want to replace "reservation":"www.. However, in your code, you've added an extra escaped quote, causing the replacement to search for "reservation":"www.", which isn't present in the string.

Simply remove that last escaped quote:

String tmp = "\"reservation\":\"www.";

Comments

Your Answer

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