Designing User Interfaces using Json

User interface API’s are sometimes great, and if done correctly, they can be used directly from code without being too verbose. Even then, separating your back-end code from the UI design keeps your code clean, and encourages better overall architecture.  Larger teams can also leverage different skill sets for designers vs. developers.

Typically, the user interface would be stored in a machine/human readable format. This makes it easier to save/load the interface using tooling/designers, or to manually hand-write via a text editor. Some formats that would be good candidates would be XML (e.g. Xaml or a custom schema), or Json.

With the latest version of Eto.Forms in github, you can now design user interfaces for WinFormsWPFGTK#iOS/MonoTouch, and Cocoa/MonoMac with a json definition. Since Json is much less verbose yet very flexible, it was a great choice. JSON.NET is one of the best .NET libraries to handle serializing/deserializing Json data to and from .NET objects, which is what I chose to use for this purpose.

An example of using json to build UI in Eto.Forms is quite simple, yet elegant:

	Title: "My Form",
	Content: {
		$type: "DynamicLayout",
		Rows: [
			{ $type: "TextBox", $name: "myTextBox" },
			null, /* expanding space */
			{ $type: "Button", Text: "Click Me!", Click: "HandleClick" }

You can easily use this json with a class like so:

public class MyForm : Form
	protected TextBox myTextBox;

	public MyForm ()
		Eto.Json.JsonReader.Load (this);

		// use myTextBox here to set initial values or bind to a model object

	protected HandleClick (object sender, EventArgs e)
		MessageBox.Show ("You clicked the button!");


This yields an interface that looks like so:

This loads the MyForm.json from the same assembly/namespace as the MyForm class. There are many other options of where and how to load the json (e.g. you can use a stream to load the json from database, external file, etc). You can also load the json without the backing class – though with the backing class, it allows you to hookup events and member variables to instances of the created controls.

An example of a more complex form can be found in the Eto.Test application here.

To try it out, clone the Eto.Forms github repository here and run the Eto.Test application.  Enjoy!

Note that Eto.Forms does indeed support xaml as well (in case you were wondering).