Posts tagged json

Creating a custom ValueType and Serialising with a custom JsonResult

When trying to serialise your model into Json you would notice the ugly way that the Microsoft JavaScriptserializer outputs dates. ie. {”d”:”\/Date(1240718400000)\/”}

This might not be a problem when you are using JQuery or Javascript, but what if your consumer is, say, an IPhone or another device? Wouldn’t you rather stick to a platform independent and recognised format?

The steps below might be a bit too drastic for your implementations, but follow them and you might also learn how to create your own ValueType and CustomJsonSerialiser all in one go!

This is what we want to accomplish. We only needed to give one converter to our CustomConverterJsonResult, but you could make this a list or even a configuration/ioc injection.

 public ActionResult Index(int? id)
 {
      return new CustomConverterJsonResult (new UnixDateTimeConverter(), _repository.GetPerson(id));
 }

Below is our custom ValueType. This allows you to do the following:

UnixDateTime uDateTime = DateTime.Now;
//OR
DateTime dateTime = uDateTime;
//OR > < => and even casting between them
public struct UnixDateTime : IComparable
{
    private static DateTime _baseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
    private readonly long _epochSeconds;

    public UnixDateTime(DateTime dateTime)
    {
       _epochSeconds = ConvertToUnixEpochSeconds(dateTime) ?? 0;
    }

    public UnixDateTime(long epochSeconds)
    {
       _epochSeconds = epochSeconds;
    }

    public override bool Equals(object obj)
    {
       if (!obj.GetType().IsAssignableFrom(typeof(UnixDateTime)))
          return false;
       return ((UnixDateTime)obj)._epochSeconds.Equals(_epochSeconds);
    }

    public bool Equals(UnixDateTime other)
    {
       return other._epochSeconds.Equals(_epochSeconds);
    }

    public override int GetHashCode()
    {
       return _epochSeconds.GetHashCode();
    }

    public int CompareTo(object obj)
    {
       return _epochSeconds.CompareTo(((UnixDateTime) obj)._epochSeconds);
    }

    public override string ToString()
    {
       return _epochSeconds.ToString();
    }

    public static bool operator >(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds > target._epochSeconds;
    }

    public static bool operator <(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds < target._epochSeconds;
    }

    public static bool operator ==(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds == target._epochSeconds;
    }

    public static bool operator !=(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds != target._epochSeconds;
    }

    public static implicit operator UnixDateTime(DateTime dateTime)
    {
       return new UnixDateTime(dateTime);
    }

    public static implicit operator UnixDateTime(long value)
    {
       return new UnixDateTime(value);
    }

    public DateTime? ToDateTime()
    {
       return ConvertFromUnixEpochSeconds(_epochSeconds);
    }

    private static long? ConvertToUnixEpochSeconds(DateTime? date)
    {
       if (!date.HasValue)
          return null;

       return (long)((DateTime)date - _baseDateTime).TotalSeconds;
    }

    private static DateTime? ConvertFromUnixEpochSeconds(long? seconds)
    {
       if (!seconds.HasValue)
          return null;

       return _baseDateTime.AddSeconds(seconds.Value);
    }
}

We then need a CustomConverterJsonResult. The reason for this is to inject the converters needed (no support for this in the normal JsonResult).

public class CustomConverterJsonResult : JsonResult
{
    private readonly JavaScriptConverter _customConverter;

    public CustomConverterJsonResult(JavaScriptConverter customConverter, object data)
    {
       _customConverter = customConverter;
       Data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
       if (context == null)
          throw new ArgumentNullException("context");

       HttpResponseBase response = context.HttpContext.Response;

       response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

       if (ContentEncoding != null)
          response.ContentEncoding = ContentEncoding;

       if (Data != null)
       {
          JavaScriptSerializer serializer = CreateJsonSerializer();
          response.Write(serializer.Serialize(Data));
       }
    }

    private JavaScriptSerializer CreateJsonSerializer()
    {
       var serializer = new JavaScriptSerializer();
       serializer.RegisterConverters(new []{_customConverter});
       return serializer;
    }
}

And finally… the JavascriptConverter.

   public class UnixDateTimeConverter : JavaScriptConverter
   {
       public override object Deserialize(IDictionary<string, object> dictionary, Type type,    JavaScriptSerializer serializer)
       {
          if(dictionary != null)
          {
             var stringValue = string.Empty + dictionary["UnixEpochSeconds"];
             if(string.IsNullOrEmpty(stringValue))
                return null;

             return new UnixDateTime(long.Parse(stringValue));
          }

          return null;
       }

       public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
       {
          var result = new Dictionary<string, object> { { "UnixEpochSeconds", obj.ToString() } };
          return result;
       }

       public override IEnumerable<Type> SupportedTypes
       {
          get { return new ReadOnlyCollection<Type>(new List<Type>(new[] {     typeof(UnixDateTime), typeof(UnixDateTime?) })); }
       }
}

This creates the following output:

{"Person":[{"Name":"John Doe","LastUpdated":[{"UnixEpochSeconds":"187653000"}]]}

jLinq – LINQ for JSON

jLinq

Sometimes I stumble accross something and immediately think “where has this been all my life?”. Finding jLinq is one of those moments.
I love Language Integrated Query (LINQ) and have used it for the last couple of years. With LINQ2NHibernate, LINQ2Lucene, LINQ2Amazon and even LINQ2Twitter emerging, it is very clear that LINQ is here to stay.

Enter jLinq from Hugoware

$.getJSON("/Person/All", function(data) {
  var results = jLinq.from(data.users)
      .startsWith("first", "a")
      .orEndsWith("y")
      .orderBy("admin", "age")
      .select();
});

You can view the basics of jLinq from this screencast.
We used jLinq to solve a very complex join operation on our JSON object and found it to be a very simple task…

  var results = jLinq.from(data.users)
    .join(data.locations, "location", "locationId", "id")
    .equals("location.state", "texas")
    .orderBy("location.city")
    .select(function(r) {
    return {
       fullname:r.first + " " + r.last,
       city:r.location.city,
       state:r.location.state
    };
});

jLinq is also very extensible and creating your own extension methods couldnt be easier…

  jLinq.extend({
    name:"startsWithLetterP",
    type:"query",
    count:0,
    method:function(q) {
        return q.helper.match(q.value, /^p/);
    }}); 

//use the new method
var results = jLinq.from(data.users)
    .startsWithLetterP("first")
    .select();

So why wait another minute, head off to experiment here right now!

Update Form Fields with JSON result in ASP.NET MVC

Wouldn’t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said “No” leave now!
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.

Lets use a simple “Person” model and have a look at the ASP.NET MVC action:

public ActionResult GetPerson(int id)
{
    var person = Context.GetPerson(id);
    return Json(new
                    {
                        success = true,
                        model = new
                                    {
                                        person.Id,
                                        person.Name,
                                        person.Surname,
                                        person.Age,

                                    }
                    });
}

As you can see this returns a DTO (data transfer object) as JSON result and is ready to be consumed via AJAX…

$.getJSON("/Person/1", function(data) {
    if (data.success) {
        $.updateForm(data.model);
    } else {
        alert("An error occurred");
    }
});

All we then need is the magical “$.updateForm” method that contains all the voodoo:

jQuery.updateForm = function(model) {
   // we iterate through all the properties
   for (var property in model) {
        // evaluate the expression to get the value
        var propertyValue = eval("model." + property);
        // and update the field
        $("#" + property).val(propertyValue);
    }
};

Currenty this will work fine for textboxes and textareas as this was all the functionality I needed for now. If anyone extends this for “select”, “checkbox”, “radiobutton” etc… please share with us so I can update this post.

Splitting your dynamic unordered list into columns

The easiest way to split your unordered list into columns is by assigning css classes.

<ul>
<li class="left">Item 1</li>
<li class="left">Item 2</li>
<li class="right_first">Item 3</li>
<li class="right">Item 4</li>
</ul>
.left {
margin-left: 0px;
}

.right {
margin-left: 50%;
}

.right_first {
margin-top: -40px;
}

If you know the size of the list then you can play around with the top margin of the “right_first” class. In our case, we do not know the size of the list, so we would have to do some black magic…

// First we calculate some variables
// the minimum column length (items / 2) at which to split into columns
var columnSplitLength = 7;
// the current would be column length
var currentColumnLength = Math.round(items.length / 2);
// is the items an odd or even length
var isOdd = (items.length > 2) != currentColumnLength;
// should we split the columns?
var shouldSplitColumns = currentColumnLength > columnSplitLength; 

var count = 1; var myLiHeight = 13; // height of each ListItem

$.each(items, function() {
    var className = shouldSplitColumns &&  (count > currentColumnLength) ? "right":"left";
    if(count == currentColumnLength+1)
        className = "right_first";
    var resultRow = $.stringFormat("<li class='{0}'>{1}</li>", [className, this.name]);
    $(resultRow).appendTo("#myUlList");
    count++;
});

// If the list length is odd, we have to add a phantom item to the right to balance
if(isOdd) {
 $("<li class='right'></li>").appendTo("#myUlList");
count++;
}
// Lastly, reset the first item of the right column to the top
$(".right_first").css("margin-left", "50%");
$(".right_first").css("margin-top", "-"+count*myLiHeight+"px");

Populating an ordered- or unordered list with JQuery via JSON

Loading dynamic data into an ordered- or unordered list cannot be simpler.

First we create a template for each LI row:

var listRow = "<li id=\"{0}\">{1}</li>";

Then we call the ajax method and handle the JSON results:

// Now using my $.stringFormat method
// (see tag 'string format')
// we append the template with the correct values to the ul or ol
$.getJSON("http://somedomain/getsomedata", function(data, status) {
   $.each(data, function() {
   var listRowPopulated = $.stringFormat(listRow, [this.id, this.title]);
      $(listRowPopulated).appendTo("#someul");
    });
});

JQuery function to populate a select box

Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the ‘populateSelect’ method in a global .js file and use it throughout your project as ‘$.populateSelect(args…)’

ASP.NET MVC Action Method

public ActionResult GetUsers()
{
     var data = Service.QueryUsers()
           .Select(x => new {value = x.Id, text = x.Name});

      return Json(data);
}

Usage:

var url = "<%=Url.Action("GetUsers", "UserController") %>";

$.getJSON(url, function(data, textstatus) {
        $.populateSelect("#someSelectBox", data);
});

Global Method:

// JQuery Method
jQuery.populateSelect = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};

Removing all Items from a select list is just as simple:

$("#mySelectList")
   .find("option")
   .remove();

And lastly how to Append or Prepend items to the list:

// Add options to the end of a select
$("#mySelectList")
    .append("");

// Add options to the start of a select
$("#mySelectList")
    .prepend("");