7

I get this response string from the Bitly api:

{ "status_code": 200,
  "status_txt": "OK",
  "data":
    { "long_url": "http:\/\/amazon.de\/",
      "url": "http:\/\/amzn.to\/1mP2o58",
      "hash": "1mP2o58",
      "global_hash": "OjQAE",
      "new_hash": 0
    }
}

How do I convert this string to a dictionary and how do I access the value for the key "url" (without all the \)

lukas
  • 2,300
  • 6
  • 28
  • 41

4 Answers4

10

This isn't just some ordinary string. This is a data structure in JSON format, a common and well-established format, originally used in Javascript but now rather common as a data transfer mechanism between services and clients.

Rather than reinventing the wheel and parsing the JSON yourself, I suggest you use an existing JSON library for C#, such as JSON.NET, which will eat up that string and parse it into .NET objects for you.

Here's a code sample, taken from JSON.NET's documentation, showing its usage:

string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
 }";

Dictionary<string, string> htmlAttributes =                 
 JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Console.WriteLine(htmlAttributes["href"]);
   // /account/login.aspx

Console.WriteLine(htmlAttributes["target"]);
   // _blank
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
5

If you add a package like Newtonsoft's Json to your project, you can deserialize the Json in to an anonymous type. You can then fetch the url from that. This is available via NuGet within Visual Studio and provides support for async or sync serialization/deserialization.

public string GetUrl(string bitlyResponse)
{
    var responseObject = new
    {
        data = new { url = string.Empty },
    };

    responseObject = JsonConvert.DeserializeAnonymousType(bitlyResponse, responseObject);
    return responseObject.data.url;
}
lukas
  • 2,300
  • 6
  • 28
  • 41
Johnathon Sullinger
  • 7,097
  • 5
  • 37
  • 102
1

I'd use JSON.NET.

http://james.newtonking.com/json

MIT License which means if you're doing anything commercial you are good.

I don't think you would want to go straight to a Dictionary, because there is some stuff there that isn't a one to one relationship. So you could make a class like the following.

public class BitlyData
{
    public string LongUrl{ get; set; }
    public string Url { get; set; }
    public string Hash { get; set; }
    public string GlobalHash { get; set; }
    public string NewHash { get; set; }
}

You could then use Json.NET to turn that String into an JObject. So we'll call your string bitlyString.

JObject bitlyObject = JObject.Parse(bitlyString);

Now we have that all that is left to do is access the data.

BitlyData theData = JsonConvert.DeserializeObject<BitlyData>(bitlyObject["data"]);

Then you can access the url (and any other pieces) using the getters.

Of course you could make it even better by having class that handles the other bits as well so you just do one serialisation.

deadwards
  • 2,109
  • 1
  • 16
  • 27
1

1)Add these classes to your project

public class Rootobject
{
    public int status_code { get; set; }
    public string status_txt { get; set; }
    public Data data { get; set; }
}

public class Data
{
    public string long_url { get; set; }
    public string url { get; set; }
    public string hash { get; set; }
    public string global_hash { get; set; }
    public int new_hash { get; set; }
}

2)Add a reference to JSON.NET

3)

   string jsonString= "YOUR JSON STRING";
   Rootobject weps = JsonConvert.DeserializeObject<Rootobject>(jsonString);

   Console.WriteLine(weps.status_code);
   if (weps.data != null)
   {
        Console.WriteLine(weps.data.url);
        Console.WriteLine(weps.data.global_hash);
        //...
   }
George Vovos
  • 7,563
  • 2
  • 22
  • 45