Skip to content

Instantly share code, notes, and snippets.

@KevM
Created July 28, 2009 15:53
Show Gist options
  • Save KevM/157469 to your computer and use it in GitHub Desktop.
Save KevM/157469 to your computer and use it in GitHub Desktop.
Extension class for turning JSON strings into objects
using System.Web.Script.Serialization;
// ^^^ for this namespace ^^^ add a reference to System.Web.Extensions
public static class StringExtentensions
{
public static string ToJson(this object objectToSerialize)
{
return new JavaScriptSerializer().Serialize(objectToSerialize);
}
public static T DeserializeJSON<T>(this string json) where T: class
{
return new JavaScriptSerializer().Deserialize<T>(json);
}
}
//usage example
var json = @"{""SearchResults"":[],""TotalNumberOfResults"":0,""RequestedNumberOfResults"":10,""StartResultIndex"":0,""SearchQuery"":""test"",""Exception"":null,""LastIndexUpdateTimestamp"":""2009-07-28T09:21:01""}";
return json.DeserializeJSON<SearchResultInformation>();
// search result objects used by the usage example. I know over the top but it doesn't hurt.
public class SearchResultInformation
{
public SearchResult[] SearchResults { get; set; }
public int TotalNumberOfResults { get; set; }
public int RequestedNumberOfResults { get; set; }
public int StartResultIndex { get; set; }
public string SearchQuery { get; set; }
public string Exception { get; set; }
public string LastIndexUpdateTimestamp { get; set; }
public SearchResultInformation() { }
public SearchResultInformation(string searchQuery, SearchResult[] searchResults, int totalResults, int startResultsIndex, int requestedNumberOfResults, string lastIndexUpdateTimestamp)
{
SearchQuery = searchQuery;
SearchResults = searchResults;
TotalNumberOfResults = totalResults;
StartResultIndex = startResultsIndex;
RequestedNumberOfResults = requestedNumberOfResults;
LastIndexUpdateTimestamp = lastIndexUpdateTimestamp;
}
public override string ToString()
{
return String.Format("Query for '{0}' returned {1} results out of {2} total starting with result {3}.", SearchQuery, SearchResults.Length, TotalNumberOfResults, StartResultIndex);
}
}
public class SearchResult
{
public float Score { get; set; }
public string Domain { get; set; }
public string Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public IDictionary<string,string> CustomFields { get; set; }
public SearchResult() { }
public SearchResult(float score, string identifier, string domain, string title, string contentSummary, IDictionary<string, string> customFields)
{
Score = score;
Id = identifier;
Domain = domain;
Title = title;
Summary = contentSummary;
CustomFields = customFields;
}
public override string ToString()
{
return String.Format("Result for {0} {1} scored {2} titled '{3}'.", Domain, Id, Score, Title);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment