Search code examples
androidjsonurlhtml-escape-characters

How to work with JSON URL


I've got a JSON object that looks something like this: (the following links are fake)

"results": {
    "urlStuff": [
        {"pic_url": "http:\/\/www.youtube.com\/inside\/kslkjfldkf\/234.jpg?v=7475646"},
        {"other_pic_url": "http:\/\/www.youtube.com\/outside\/kslkjfldkf\/234.jpg?v=7475646"}
    ]
}

or something to that effect. My question is, why do the urls have escape characters if they are already strings? I am having to get rid of them to make the method calls on the URL to get the pics. Am I missing something? I am using Android to make this call.

Thanks, Matt


Solution

  • why do the urls have escape characters if they are already strings?

    They have escape characters because they are strings -- specifically, because they are JSON strings they have JSON string escape characters, and the entity that sent them to you decided to use the option to escape the solidus. For more information on why the sending entity may have made that choice, see the Why does the Groovy JSONBuilder escape slashes in URLs? post.

    I am having to get rid of them to make the method calls on the URL to get the pics. Am I missing something?

    Take the easy route and just use a decent JSON parsing API to take care of automatically removing the JSON escape characters for you, when translating the JSON string into a Java String. Android has such a built-in JSON library available.

    package com.stackoverflow.q6564078;
    
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    
    public class Foo extends Activity
    {
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        // {"pic_url": "http:\/\/www.youtube.com\/inside\/kslkjfldkf\/234.jpg?v=7475646"}
        String jsonInput = "{\"pic_url\": \"http:\\/\\/www.youtube.com\\/inside\\/kslkjfldkf\\/234.jpg?v=7475646\"}";
        Log.d("JSON INPUT", jsonInput);
        // output: {"pic_url": "http:\/\/www.youtube.com\/inside\/kslkjfldkf\/234.jpg?v=7475646"}
    
        try
        {
          JSONObject jsonObject = new JSONObject(jsonInput);
          String javaUrlString = jsonObject.getString("pic_url");
          Log.d("JAVA URL STRING", javaUrlString);
          // output: http://www.youtube.com/inside/kslkjfldkf/234.jpg?v=7475646
        }
        catch (Exception e)
        {
          throw new RuntimeException(e);
        }
      }
    }