Using Json.NET with MonoTouch

Published 11/21/2009 by brettnagy in iPhone, Mono
Tags: , ,

I make heavy use of external data in my iPhone applications and for that I rely on JSON. Our server-side data access moved to JSON a while ago as it allows us to support heterogeneous caller types, such as web browsers with JavaScript, server processes and (as seen here) mobile apps.

The latest version of Json.NET is an excellent library. There were a few gotchas for me, when getting it to work with MonoTouch.

1. Project Settings

After downloading the source code, add the Newtonsoft.Json project to your solution. Control+Click the project name and select 'Options'

From the General section, set the Runtime version to 'Mono for iPhone'

General Options Window

Next, from the Compiler section, add the SILVERLIGHT and PocketPC symbols. Be sure both are added to Debug and Release configurations.

Compiler Options Window

2. Using Json.NET in C#

The MonoTouch linker is insanely slick. It's clever enough to exclude unused code from the final, iPhone native executable. However, this can cause issues with reflection based code as come run time, methods and properties you clearly see in source code are just not present or detectable using reflection.

This caught me out at first, as during Json.NET deserialization none of my class properties were being bound to and Json.NET kept complaining that my classes had no default constructor, when they clearly did.

Of course, MonoTouch designers have already thought of this and have given us the MonoTouch.Foundation.Preserve attribute. Adding this to methods or properties will prevent the linker from removing them. The classes I now use for deserialization look (something) like this:

public class Avatar
{
	[MonoTouch.Foundation.Preserve]
	public Avatar(){}
		
	[MonoTouch.Foundation.Preserve, JsonProperty("url")]
	public string Url { get; set; }
		
	[MonoTouch.Foundation.Preserve, JsonProperty("size")]
	public string Size { get; set; }
}

Here is the code I use to access the external JSON data and download it into a string instance:

Uri address = new Uri(SERVICE_URL);
			
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
			
string responseBody = null;
try
{
	UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
				
	using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
	{    
	    var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
				    
	    responseBody = reader.ReadToEnd();  
	} 
}
catch ( WebException we )
{
	Console.WriteLine( we.Message );
}
finally
{
	UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
}

Now I can use something similar to the following code to take that string and deserialize it into my class instances:

List<Avatar> memberAvatars = JsonConvert.DeserializeObject<List<Avatar>>( responseBody );

Comments

MonoTouch.Info

Monday, November 16, 2009 7:59 PM

trackback

Using Json.NET with MonoTouch

Thank you for submitting this entry - Trackback from MonoTouch.Info

Jb Evain France

Wednesday, November 18, 2009 12:40 AM

Jb Evain

Hey Brett,

Nice post!

Alternatively, you can put a `[Preserve (AllMembers = true)]` on the Avatar type, it will preserve everything inside it!

Best,

brettnagy United States

Thursday, November 19, 2009 7:45 AM

brettnagy

Great idea. Thanks!

GoiPhone United States

Friday, November 27, 2009 1:08 PM

GoiPhone

Hi Brett,

I am trying to follow your example here since it is a terrific idea to transport lightweight JSon objects over the wire versus full blown .net objects. The problem I have is, when compiling the NewonSoft.JSon project inside monodevelop, I got the following error message,

Error: /var/folders/+2/+2lQV79J2RWIz++1Yrck-++++TI/-Tmp-/tmp1c430626.tmp (Newtonsoft.Json)

I cannot figure out what that is (I am new to mac development - that is why we are trying to use monotouch), can you help me out what this is?

Thanks

brettnagy United States

Sunday, November 29, 2009 4:23 PM

brettnagy

I've had the same problem and honestly didn't get to the cause. My (impatient) solution was to remove the project and re-add it. Low tech for sure, but it worked!

Online bachelor degree United States

Tuesday, February 16, 2010 9:27 PM

Online bachelor degree

Hi.. i'm first time here.. but it look like interesting here.. i hope you can blog more about this..

Johnny entertainment Australia

Tuesday, March 09, 2010 3:09 PM

Johnny entertainment

Hi, It's a rare find for a nice blog like this. I enjoyed it. Kudos to you. Have a nice day!

online games free United States

Sunday, March 14, 2010 3:56 AM

online games free

Hey, how does someone subscribe to your RSS Feed?

Nathaniel Pedrotti United States

Monday, March 15, 2010 11:20 AM

Nathaniel Pedrotti

hey,

Well, getting a free iPhone is very easy. Ya just gotta find the right place. My 2 cents. Did you know there are a plethora of contests that ya can sign up for. Many really do offer free stuff ... heck, it's how I got my free iPhone Smile

stock trading United States

Tuesday, March 16, 2010 12:29 PM

stock trading

I've stopped by here a few times and it seems like your post get more informative each time. Keep it up I enjoy reading them.

loans for people with bad credit United States

Wednesday, March 17, 2010 2:05 AM

loans for people with bad credit

Have you considered adding some sort of bookmarking buttons or links to your blog posts?

Daniel Millions United States

Wednesday, March 17, 2010 5:54 PM

Daniel Millions

I wasn't sure where to post this but I would like to add your website to one of my web directories. Please contact me at your convience because I will only list webistes with the webmasters consent - thank you.

mobile phone deals United States

Friday, March 19, 2010 9:00 PM

mobile phone deals

I enjoy reading a post that will make one think.

Really thankful to you for providing us this information.

keep it up.

Stock Trading System United States

Sunday, March 21, 2010 8:51 AM

Stock Trading System

I am very impressed with this blog post. I hope you will continue to publish entertaining blog posts that will entertain your readers. I will be visiting your blog frequently.

metal roofing materials Poland

Sunday, March 21, 2010 9:54 AM

metal roofing materials

I am quite interesting in this topic hope you will elaborate more on it in future posts

laptop spares United States

Monday, March 22, 2010 6:29 AM

laptop spares

Hi webmaster - This is by far the best looking site I’ve seen. It was completely easy to navigate and it was easy to look for the information I needed. Fantastic layout and great content! Every site should have that. Awesome job

Jamorama United States

Monday, March 22, 2010 10:43 PM

Jamorama

hopefully this post doesn't appear multiple times (it seems to freeze once i try to post my comment.. not sure if it's actually posting), but all I really wanted to say was wonderful post and thanks for sharing.

guitar lessons for beginners United States

Wednesday, March 24, 2010 11:27 AM

guitar lessons for beginners

can anyone tell me how to get those little avatars to show up in my comments section? thanks!

agilemobility.net

Thursday, October 14, 2010 7:03 PM

pingback

Pingback from agilemobility.net

Json.net library | Agile mobility

Comments are closed

Brett Nagy

Software development, engineering and everything in between