tags:

views:

103

answers:

2

From a .NET assembly (non-web app)...

The normal response from Bit.ly is somewhat in the form of below. What is recommended way of consuming that result so that I can easily get the value of the shortUrl field? Since the original URL comes back as a "key", building a model class to deserialize it to and using LINQ does not seem to make sense. In Javascript, a simple .eval would work but what is the recommended approach in .NET since the model would be dynamic?

{ 
    "errorCode": 0, 
    "errorMessage": "", 
    "results": 
    { 
        "http://www.google.com/": 
        { 
            "hash": "xxxxxx", 
            "shortKeywordUrl": "", 
            "shortUrl": "http://bit.ly/xxxxx", 
            "userHash": "1F5ewS" 
        } 
    }, 
    "statusCode": "OK" 
}
A: 

well, let me google that for you http://msdn.microsoft.com/en-us/library/bb412179.aspx

Andrey
that part is easy. This is great if you know what the keys are. However, with bit.ly, the value you pass in becomes the returned key so you cannot build a class at design time
Cody C
ok. i tried few requests and it it seems to me that schema is rather simple. try different combinations and you will know it. also you can request xml, not json.
Andrey
For this exercise, I purposely want JSON. Maybe I'm missing something. The schema is simple, but dynamic. So, http://www.google.com would essentially become a property or key of my object but since that changes on each request, I wouldn't be able to create that object definition at design time would I?
Cody C
+1  A: 

.NET provides a mechanism similar to eval (JavaScriptSerializer). If you just need to parse out a few values the code would look like this:

var serializer = new JavaScriptSerializer();
var values = serializer.Deserialize<IDictionary<string,object>>( jsonData );
var results = values["results"] as IDictionary<string,object>;
var google = results["http://www.google.com/"] as IDictionary<string,object>;
var shortUrl = results[ "shortUrl" ];

If you'll be accessing the other data, you can create your own DTO and have the serializer map the JSON data to that.

public class Bitly
{
    public string hash{ get; set; }
    public string shortKeywordUrl{ get; set; }
    public string shortUrl{ get; set; }
    public string userHash{ get; set; }
}

var google = serializer.ConvertToType<Bitly>( results["http://www.google.com/"] );
Paul Alexander