Monday, July 3rd, 2006

Json.NET: Library to help with .NET – JS communication

Category: .NET, JavaScript, Library

James Newton-King has released a new library Json.NET that aims to provide JSON .NET API for simply and safely reading and writing valid JSON text. At the core of Json.NET, similar to the .NET XML APIs, are two classes: JsonReader and JsonWriter. Also like XML in .NET, Json.NET includes a JsonSerializer class.

Reading JSON

  1. string jsonText = "['JSON!',1,true,{property:'value'}]";
  2.  
  3. JsonReader reader = new JsonReader(new StringReader(jsonText));
  4.  
  5. Console.WriteLine("TokenType\t\tValueType\t\tValue");
  6.  
  7. while (reader.Read())
  8. {
  9.     Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value))
  10. }

Writing JSON

  1. StringWriter sw = new StringWriter();
  2. JsonWriter writer = new JsonWriter(sw);
  3.  
  4. writer.WriteStartArray();
  5. writer.WriteValue("JSON!");
  6. writer.WriteValue(1);
  7. writer.WriteValue(true);
  8. writer.WriteStartObject();
  9. writer.WritePropertyName("property");
  10. writer.WriteValue("value");
  11. writer.WriteEndObject();
  12. writer.WriteEndArray();
  13.  
  14. writer.Flush();
  15.  
  16. string jsonText = sw.GetStringBuilder().ToString();
  17.  
  18. Console.WriteLine(jsonText);
  19. // ['JSON!',1,true,{property:'value'}]

Visit the Json.NET homepage

Posted by Dion Almaer at 9:14 am
27 Comments

+++--
3.8 rating from 62 votes

27 Comments »

Comments feed TrackBack URI

Looks promising, though I’d expect the JSON writer to work more like a SOAP or XML-RPC bridge, where you just give it .NET datatypes and it generates the appropriate JSON code.

Comment by Steve Ivy — July 3, 2006

I agree with Steve. You should be able to send it native .NET datatypes and have it spit out the right JSON code. This way seems like you’re having to build the JSON string from scratch (practically) and not saving any time at all?

Comment by Jon — July 3, 2006

That is painful, isn’t it? But if you follow the link to the site, you’ll see that there is also a JsonSerializer object that converts .NET objects to JSON code. Much better!

Comment by Michael Geary — July 3, 2006

See the JSON de-/serializer inside the Ajax.NET Professional library which will handle any .NET datatype in both directions.

Comment by Michael Schwarz — July 3, 2006

The Json.NET serializer appears to handle .NET datatypes in both directions also.

Comment by Alan — July 3, 2006

It looks like it produces invalid JSON. Valid JSON uses double quotes around strings and always quotes quotes property names – so that last example should produce:

[“JSON!”, 1, true, {“property”:”value”}]

Comment by Simon Willison — July 4, 2006

After setting a couple of properties on the JsonWriter class (QuoteChar to double quotes, QuoteName to true) you can generate that output Simon.

By default what it outputs now is a valid JavaScript object literal but you’re right that it doesn’t exactly conform to the spec by default. Internally it doesn’t matter as the JsonReader class is pretty robust in that it handles all the different situations, but for the sake of other readers that might be something to change next version.

Comment by James Newton-King — July 4, 2006

In rails, I can call the .to_json method on any object. For serialization, that’s the kind of API I’d want. Anything else is too verbose.

Comment by beppu — July 4, 2006

The example code given is not just painfully verbose, it actually ends up making your code really ugly, fragile and inflexible for anything that is not trivial. It forces you to:
* structure your code according to the tree structure of the JSON
* or have a separate method that you pass in the message parameters and create the JSON object
and it limits how you can build up parts of a message to make a whole.

I have experience with this because I implemented the same style API in Delphi and it really sucked.

[I replaced it with variants objects/arrays which is clean, although disadvantage of overhead with variants, but advantage that is good for receiving JSON]

Comment by Morris — July 4, 2006

Serializing Objects as JavaScript using Atlas, JSON.NET and AjaxPro

Trackback by ComputerZen.com - Scott Hanselman — July 4, 2006

beppu there is a helper method on the JavaScriptConvert class to quickly serialize objects.

string jsonText = JavaScriptConvert.SerializeObject(value);

Morris the JsonWriter and JsonReader are underlying classes and you would really only use them if you wanted exact control over what is written. Normally you would use the JsonSerializer and methods like the one above to convert to and from JSON.

Comment by James Newton-King — July 5, 2006

Cool. That sounds a lot better. :-)

Comment by beppu — July 5, 2006

[…] Een heus berichtje voor de dotnetters onder ons. De Ajaxian meldt dat er een utility library is ontwikkeld voor het gebruik van JSON binnen ASP.NET webapplicaties. De library biedt een makkelijk te gebruiken JsonWriter: PLAIN TEXT C#: […]

Pingback by JSON.NET Library | Scriptorama — July 6, 2006

I still get a lot of errors when serializing .net standard types like TimeSpan or DateTime. I use this in my web mailer app with another library without having those problems. What I’m doing wrong?

Comment by Scott — July 10, 2006

I’d like to know what are the benefits using JSON.NET instead of i.e. Atlas or AjaxPro. I only need JSON in web sites, not Windows Forms or Services.

Comment by Scott — July 10, 2006

It is not working with a lot of data types… :(

Comment by Jeffry — July 10, 2006

I get it not running with .NET 1.1, is there a version conflict? Or do I need to configure something in app.config?

Comment by Manuela — July 11, 2006

Json.NET has been updated to 1.1 and fixes a number of bugs around serialization.

While it is now improved not every class can be serialized and deserialized. Some have self referencing loops for example which can cause problems.

Comment by James Newton-King — July 11, 2006

Json.NET has been updated to 1.1 and fixes a number of bugs around serialization.

Comment by ePeaksoft — November 15, 2006

Can dojo be used in Json.net? how

Comment by hanker — March 13, 2007

How does it handle inherited classes? I see self referencing exceptions happening…

Comment by Alex Egg — August 14, 2007

Unfortunately does not run under .net CF 2.0. E.g. System.ComponentModel.TypeDescriptor seems to be not available.

Regards

Comment by neil — August 27, 2007

Can anybody figure out how to deserialize a javascript array into an array of string? The documentation on this class is non-existent!

Comment by Dan — September 5, 2007

Unfortunately the documentation for the Json.Net library is incredibly lacking. After trying out about a billion different things, I’ve finally figured out how to Deserialize a JavaScript Array of Object Literals in JSON format into something usable on the .Net side. I’m going to try and insert some formatted C# here, hopefully the comment form doesn’t destroy it!

1. Create a custom class which describes the Object Literals that you’ll be passing in:

///
/// Used for deserializing JSON objects from JavaScript
///
public class JsonSeat {
///
/// The seat ID (SeatNo)
///
public int id;
///
/// Name of the Price Type
///
public string priceType;
///
/// Number of the Price Type
///
public int priceTypeID;
///
/// Price of the ticket
///
public string price;
///
/// Name of the seating section
///
public string section;
///
/// The Row and Number of the seat
///
public string rowAndNumber;
///
/// The HyperLink.ClientID of the seat element
///
public string anchorID;
}

2. Deserialize your JSON string into a List of your custom classes:

List selectedSeats = (List) JavaScriptConvert.DeserializeObject(txt_Selection.Text,typeof(List));

3. You can now iterate through your objects and access them as expected:

foreach (JsonSeat seat in selectedSeats) {
lit_Temp.Text += string.Format("Seat: {0}; {1}{2}",seat.id,seat.rowAndNumber,"");
}

Comment by Dan — September 6, 2007

Hmmm, pretty much killed it entirely, let’s try it again!

Unfortunately the documentation for the Json.Net library is incredibly lacking. After trying out about a billion different things, I’ve finally figured out how to Deserialize a JavaScript Array of Object Literals in JSON format into something usable on the .Net side. I’m going to try and insert some formatted C# here, hopefully the comment form doesn’t destroy it!

1. Create a custom class which describes the Object Literals that you’ll be passing in:

/// Used for deserializing JSON objects from JavaScript
public class JsonSeat {
/// The seat ID (SeatNo)
public int id;
/// Name of the Price Type
public string priceType;
/// Number of the Price Type
public int priceTypeID;
/// Price of the ticket
public string price;
/// Name of the seating section
public string section;
/// The Row and Number of the seat
public string rowAndNumber;
/// The HyperLink.ClientID of the seat <a> element
public string anchorID;
}

2. Deserialize your JSON string into a List of your custom classes:

List<JsonSeat> selectedSeats = (List<JsonSeat>) JavaScriptConvert.DeserializeObject(txt_Selection.Text,typeof(List<JsonSeat>));

3. You can now iterate through your objects and access them as expected:

foreach (JsonSeat seat in selectedSeats) {
lit_Temp.Text += string.Format("Seat: {0}; {1}{2}",seat.id,seat.rowAndNumber,"");
}

Comment by Dan — September 6, 2007

One last try at posting this code:

Unfortunately the documentation for the Json.Net library is incredibly lacking. After trying out about a billion different things, I’ve finally figured out how to Deserialize a JavaScript Array of Object Literals in JSON format into something usable on the .Net side.

1. Create a custom class which describes the Object Literals that you’ll be passing in:


/// Used for deserializing JSON objects from JavaScript
public class JsonSeat {
/// The seat ID (SeatNo)
public int id;
/// Name of the Price Type
public string priceType;
/// Number of the Price Type
public int priceTypeID;
/// Price of the ticket
public string price;
/// Name of the seating section
public string section;
/// The Row and Number of the seat
public string rowAndNumber;
/// The HyperLink.ClientID of the seat <a> element
public string anchorID;
}

2. Deserialize your JSON string into a List of your custom classes:


List<JsonSeat> selectedSeats = (List<JsonSeat>) JavaScriptConvert.DeserializeObject(txt_Selection.Text,typeof(List<JsonSeat>));

3. You can now iterate through your objects and access them as expected:


foreach (JsonSeat seat in selectedSeats) {
lit_Temp.Text += string.Format("Seat: {0}; {1}{2}",seat.id,seat.rowAndNumber,"<br />");
}

Comment by Dan — September 6, 2007

Leave a comment

You must be logged in to post a comment.