A couple of days ago I wrote a .NET API for Last.Fm's Autocomplete Search...
Make sure you have the latest fastJson libraries / source code, compile and ejoy!
Class Definition
public class LastFmAutoComplete
{
public string Artist { get; set; }
public string Album { get; set; }
public string Track { get; set; }
public TimeSpan Duration { get; set; }
public string Id { get; set; }
public string Image { get; set; }
public string Reach { get; set; }
public string Resid { get; set; }
public AutoCompleteType Restype { get; set; }
public string Weight { get; set; }
public static AutoCompleteType ParseAutoCompleteType(string input)
{
var inputInt = int.Parse(input);
return (AutoCompleteType)inputInt;
}
public enum AutoCompleteType
{
Artist = 6,
Album = 8,
Group = 20,
Tag = 32,
Track = 9,
Label = 10,
Event = 29
}
}
The API Method
public List<LastFmAutoComplete> RequestAutocomplete(string query)
{
var returnValue = new List<LastFmAutoComplete>();
if (string.IsNullOrEmpty(query))
return returnValue;
using (var autoCompleteDownloader = new WebClient())
{
var jsonString = autoCompleteDownloader.DownloadString(string.Format("http://last.fm/search/autocomplete?q={0}&force=1", query));
var jsonParser = new fastJSON.JsonParser(jsonString);
var decodedJson = (Dictionary<string, object>)jsonParser.Decode();
var responseBlock = (Dictionary<string, object>)decodedJson["response"];
var docsBlock = (ArrayList)responseBlock["docs"];
foreach (Dictionary<string, object> doc in docsBlock)
{
var tmpAutoCompleteData = new LastFmAutoComplete
{
Restype = LastFmAutoComplete.ParseAutoCompleteType(doc["restype"].ToString())
};
if (tmpAutoCompleteData.Restype == LastFmAutoComplete.AutoCompleteType.Tag || tmpAutoCompleteData.Restype == LastFmAutoComplete.AutoCompleteType.Group || tmpAutoCompleteData.Restype == LastFmAutoComplete.AutoCompleteType.Label || tmpAutoCompleteData.Restype == LastFmAutoComplete.AutoCompleteType.Event)
break;
tmpAutoCompleteData.Artist = doc["artist"].ToString();
if (doc.ContainsKey("album"))
tmpAutoCompleteData.Album = doc["album"].ToString();
if (doc.ContainsKey("track"))
tmpAutoCompleteData.Track = doc["track"].ToString();
if (doc.ContainsKey("duration"))
tmpAutoCompleteData.Duration = TimeSpan.FromSeconds(int.Parse(doc["duration"].ToString()));
tmpAutoCompleteData.Id = doc["id"].ToString();
if (doc.ContainsKey("image"))
tmpAutoCompleteData.Image = string.Format("http://userserve-ak.last.fm/serve/64s/{0}", doc["image"]);
tmpAutoCompleteData.Reach = doc["reach"].ToString();
tmpAutoCompleteData.Resid = doc["resid"].ToString();
tmpAutoCompleteData.Weight = doc["weight"].ToString();
returnValue.Add(tmpAutoCompleteData);
}
return returnValue;
}
}
