Deserializing JSON to a .NET Object

Generally in .NET MVC you would use the default model binders to deserialize JSON to a .NET object. However, there are some cases, involving “complex” collections, where this becomes a bit tedious to do. Microsoft provides a few ways around this, but none are satisfactory. Unlike the default model binders, the JavaScriptSerializer provides support for deserializing JSON to a .NET object with complex collections.

Take the following simple class and method signature for example:

// simple class
public class SaveInformation
{
    public string Name { get; set; }
    public Dictionary<string, List<SaveItem>> Components { get; set; }
}

// method signature
public ActionResult Save(SaveInformation saveInformation)

Below I’ve included some simple JSON that we will pass to .NET via AJAX:

{"SaveToSession":false,"Name":"My Stupendous Thing","Components":{"Component1":[{"ProductId":"1234"}]}}

We are passing the JSON to .NET using AJAX with the “application/json” contentType. Because we are using the “application/json” contentType, .NET will automatically call the JsonValueProviderFactory and map the information over to our SaveInformation model. It seems pretty straight forward, the Save method will receive a SaveInformation object when it is called.

Not so straightforward unfortunately, the Save method does receive a SaveInformation object. If we inspect our SaveInformation object we see the Name is populated perfectly fine, but the Components dictionary ends up being null.

The reason for this? It seems that the JsonValueProviderFactory doesn’t fully support pure JSON syntax. In order for .NET to properly parse a complex collection, you actually have to give it a numerical index.

From http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:

Though it’s somewhat counterintuitive, JSON requests have the same requirements—they, too, must adhere to the form post naming syntax. Take, for example, the JSON payload for the previous UnitPrice collection. The pure JSON array syntax for this data would be represented as:

[
    { "Code": "USD", "Amount": 100.00 },
    { "Code": "EUR", "Amount": 73.64 }
]

However, the default value providers and model binders require the data to be represented as a JSON form post:

{
    "UnitPrice[0].Code": "USD",
    "UnitPrice[0].Amount": 100.00,

    "UnitPrice[1].Code": "EUR",
    "UnitPrice[1].Amount": 73.64
}

I know right? It was hard for me to read this as well due to the anime-sized tears in my normal-sized eyes. The problem is, no browser I know of has a JSON.serializeForDotNet function. So this leaves us with two options, make our own JSON serializer, or make our own ValueProvider/ModelBinder. Neither of these options sounded very appealing to me, so I went with the hidden third option. Pass in a string :)

You can use the JavaScriptSerializer class, located in System.Web.Script.Serialization, to deserialize JSON information and, as an added bonus, it actually handles properly formatted pure JSON!

So, the new method looks like this. We pass in a string value and deserialize it using the JavaScriptSerializer. Now we receive a SaveInformation object with a fully populated Components dictionary.

public ActionResult Save(string saveInformation)
{
    // instantiate a JavaScriptSerializer
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    // use the JavaScriptSerializer to deserialize our json into the expected object
    SaveInformation saveInformationObject = serializer.Deserialize<SaveInformation>(saveInformation);

URF! Ultra Rapid Fire mode needs to come back!

URF Login on April 1

URF Login on April 1

Riot introduced Ultra Rapid Fire mode into League of Legends on April 1 as an April fools joke. However, the community saw it as far less than a joke. The reasons that Riot gave for introducing URF included aboloshing “anti-fun”. I think they were on to something.

Here are the basics that were granted in Ultra Rapid Fire mode:

  1. Mana and Energy costs were removed (no need to manage that resource).
  2. Ranged champions attackspeed increased by 100%.
  3. Every champion begins the game with 80% cooldown reduction on abilities and spells.

This handy tool tip explains the gist of it:

The only way to play League anymore.

The only way to play League anymore.

There were some additional features I liked, movement speed was increased, so I didn’t have to buy boots every single game.

I played URF everyday since April 1st when it came out. I was very happy that (after the community begged and begged) Riot extended it for another week. But, alas, Riot ended it last night, April 13. I played one last game with ‘Vi’ which we won, and waved goodbye.

At the time I thought that everything would be fine. I’d go back to playing normal mode and it’d be just as fun as it was before. This morning I logged in and played a match with Vi on the Twisted Treeline map. It was very disappointing.

The movement speed was too slow, even with Boots of Speed. Waiting for cooldowns to proc was annoying. It took forever to build any items (even on Treeline). I was overwhelmed with a feeling of general frustration. The game had become less fun.

It used to be that I looked forward to playing League of Legends. However, when I think about playing League of Legends now I just feel extremely disappointed. I don’t really want to play anymore. It’s not that the game is bad, it’s a good game. But, after seeing how fun it could be it’s just not as interesting anymore.

Other people have noticed the same thing. The community is longing for URF to come back. Notice some of the response.

So with that said, I think I’m going to be taking a break from League of Legends. It’ll give me some time to finish some other games I’ve been needing to finish, like Tomb Raider 2013. Maybe I’ll come back later refreshed and find the game to be fun again. Maybe I’ll get fed up and program my own URF mode game. Or… maybe it is just time to say goodbye.

Pick of the Week for September 16 – Tonight Alive

I just heard about this band the other day from my one of my friends during a text conversation. He thought it would be right up my alley, and well he was right. The name of the band is “Tonight Alive“. They are a five piece pop punk band from Australia. That’s right, Australia!

Tonight Alive has been around since 2008, so I would consider them a newer band. Some people have compared them to Paramore… but I think they’ve got their own little spunk that sets them apart. In either case they are a good band and I think you should give them a listen.

The song I’ve picked is from the new album, “The Other Side”. The album was just released on September 6, so it is brand new! I’ve actually picked two songs off this album. The reason is, well I just can’t pick between the two!

The first song I’ve picked is titled “The Other Side”, it’s the title track off the album. I picked this song because of how heartfelt it is. You can truly feel the emotion put into the song, from the way that it is sung to the way that it is played. It’s a great song and you can listen to it below.

The second song I’ve picked is titled “The Fire”. It is the song that I originally intended to put on this blog before I started struggling with “The Other Side”. I really enjoy the crisp guitar in this song. I especially like the guitars in the bridge. The song is sung very well and I find myself wanting to belt out parts of it with the singer.

Buy “The Fire” here.
Buy “The Other Side” here.

The Other Side

The Fire

Pick of the Week for September 9 – blessthefall

Wow! It has been a long time. The good news is that we are finally moved into our new house (although I haven’t got my computer up and running yet, tonight!). We have been homeless since August 15 and it sure feels good to have a home again. I’ve been up late painting and moving things and changing locks and installing blinds. It’s been crazy!

Alright, so the pick of the week is a song called “You Wear a Crown but You’re No King” from blessthefall’s new album “Hollow Bodies”. It’s pretty dang good! Give it a listen below and let me know what you think in the comments section below! Do it!

Buy You Wear a Crown but You’re No King

Pick of the Week for August 12

The pick of the week is from Dispatch one of my top five all time artists. I’ve only said that about one artist before. One of the things that I’ve always thought was a bummer is that I didn’t start listening to Dispatch until after they decided to call it quits! Yep! I started listening to them in 2004 after one of my friends introduced me to them. This just happenned to be right after there farewell concert, which, according to there website, was the largest independent music event in history. Needless to say, but I will say it anyways. It was only a few weeks before I had all of there albums.

This song comes from there first album, Silent Steeples. Silent Steeples is probably my favorite album by Dispatch. Each of there albums has a unique sound to it. Silent Steeples is more accoustic/folk rock whereas Bang Bang had more of a reggae/ska influence to it.

Well, I would love to go on and on about Dispatch, but I should probably just post the song already! The name of the song is “Bridges”. You can buy “Bridges” by Dispatch here or listen below.

Owl City to be Blamed for Recent Popularity of Electronically Driven Music

I just thought I would post this here while I was thinking of it. I believe that Owl City is to blame for the recent propagation and proliferation of electronic and keyboard driven music making it’s way into the mainstream. Granted, keyboards and synths have been around for a long time and have always had a following. But I believe that keyboard and synth driven music is just going to become more popular over the next few years. Adam Young, I believe, was the catalyst that helped spawn this growing trend in the popularity of electonically driven music.

So let’s say a big thanks to Owl City. Personally, I think the world could always use more keytar.

Taco Bell Removes the Enchirito from Menu

**EDIT 09/20/2013 **

I recently went back to Taco Bell. As it turns out they have put the Enchirito back on the menu. When I asked why, they told me that a lot of people were unhappy and wanted it back. So good work people!

**END EDIT**

Oh Taco Bell. You have done this to me before and you are doing it to me again. When are you going to learn that taking things off your menu is a BAD thing? It is especially bad when you “take” something off the menu and replace it with the same thing albeit more expensive.

A couple of years ago Taco Bell removed the Nacho Cheese Chalupa from it’s menu. (It was probably a couple of years ago although it could’ve been more recently). This made me mad. Let me tell you what I say when I order from Taco Bell. “Hi Taco Bell Person, I’d like 2 bean burritos, a Nacho Cheese Chalupa and an Enchirito”. That’s it! That is what I always had. So imagine my surprise when one day I say my normal order and the response from the other end is “We don’t sell Nacho Cheese Chalupas anymore.” And so I said, “What?…”.

What?...

What?…

Well that was a bad day. But I quickly learned how to get around it by being a super annoying customer. That’s right, my future orders went a little like this.

I’d like two bean burritos, a Nacho Cheese Chalupa, and an Enchirito please.
We don’t sell Nacho Cheese Chalupa’s anymore.
Oh really…? Hrmmm. Well then I would like a Supreme chalupa with no sour cream.
No sour cream?
Yes. No sour cream. Oh and can you add Nacho Cheese to that too?
A Supreme Chalupa with no sour cream and nacho cheese?
Yes.

So, in case you are wondering how to get a Nacho Cheese Chalupa, that’s how.

So… same story no happy ending yet. Today I go to Taco Bell and I order my order. This time they say “We don’t sell enchiritos anymore”. And so I said “What?…”

What?...

What?…

So, as it turns out, they are selling Enchiritos, they’ve just renamed them and made them more expensive. They are now called “Smothered Burritos” and they come with Sourcream on them in addition to the normal stuff. Can you say argggggg? I can. You should try it, I think you probably could.

I’m sure I’m not the only one who thinks it’s LAME to rename an item on your menu and make it more expensive. Then again I guess they can do what they want to do… be stupid.

Pick of the Week for August 5th

Alright. I decided that rather than pushing the pick of the week off to the end of the week, like I did last week, I would just post it right at the beginning. No excuses!

It took me a while to decide which song to post here. I knew I wanted to post a song by The Birthday Massacre, I just had no idea which one to post! Now if you don’t know who The Birthday Massacre is, you are missing out! You might not think so my the name, but they are awesome. The have a seemingly perfect blend of 80′s bands like The Cure with modern day rock. I dig them, and you probably will too!

As I mentioned, it took me a while to decide which song to post on here. I decided, hey it’s my blog, so I can always post another TBM song at a later date. In any case, the fact that I had such a hard time deciding is a testament to the band in and of itself. The fact is, the entire Pins and Needles album is good and you should probably go buy it, right now.

The name of the song is “Sideways” and the reason it won out over the other TBM songs is because of the intro. The intro to this song is dang good! Listen below and buy the song here.