1

I have below json stored in sharedPref as a single line string

[
   {
      "url":"http:\/\/google.com",
      "feedType":"Automotive"
   },
   {
      "url":"http:\/\/google.com",
      "feedType":"Automotive"
   }
]

I am checking that url is already present in json string using below code but its not working since json is escaped with \ backslash.

String url = "http://google.com";
String jsonString = '[{"url":"http:\/\/google.com","feedType":"Automotive"},{"url":"http:\/\/google.com","feedType":"Automotive"}]';

if(jsonString.contains(url)) {
      Toast.makeText(context, "URL already exists.", Toast.LENGTH_LONG).show();
      return false;
}

Please help how can i check that url is already exist in string to avoid dupes.

2 Answers 2

1

This will ignore the backslashes when comparing the Strings:

String url = "http://google.com";
String jsonString = //get it from SharedPreferences

if(jsonString.replace("\\", "").contains(url)) {
      Toast.makeText(context, "URL already exists.", Toast.LENGTH_LONG).show();
}

Note the use of replace("\\", "").

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

Comments

0

I've got 2 solution in mind.

First, the hard one, is to remove escape characters by deserializing your json string into objects and then compare url.

Second one is to remove escape characters by yourself.

2 Comments

ya as @JohnasCz said, I think first one is good for simplicity, it will be overkill to go an loop every object and check the it has the url :)
Choose that suits best to your app :)

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.