====== Json.NET ======
===== New things =====
I have been using Json.NET for a lot of time. It is simple and has been evolving during all this time. In this section I add some of those characteristics worth of being maintained.
==== Characteristics ====
=== Deserialize an anonymous object ===
var definition = new { token = "" };
var token = JsonConvert.DeserializeAnonymousType(jsonresult, definition);
===== Basico para .NET 3.5 =====
==== Utilización ====
A partir de la siguiente clase...
public class MyClass
{
public string name { get; set; }
public int age { get; set; }
}
... creamos el siguiente objeto:
MyClass MyObject = new MyClass() { name = "Pedro", age = 49 };
Podemos serializarlo como JSON:
string json = Newtonsoft.Json.JsonConvert.SerializeObject(MyObject);
Y deserializarlo:
MyClass obj = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(json, MyObject.GetType());
==== Links ====
* [[http://james.newtonking.com/projects/json-net.aspx]], página de ayuda y de presentación de la librería.
* [[http://json.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29756]], página oficial de descarga.
* {{fw:othersnet:json35b4.zip}}, versión a partir de la que se ha trabajado.
===== Basico para .NET 2.0 =====
==== Utilización ====
Podemos serializar un objeto de la siguiente forma:
public string getJSON ()
{
StringWriter sw = new StringWriter();
Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("swap");
writer.WriteValue(this.swap);
writer.WritePropertyName("mem");
writer.WriteValue(this.mem);
writer.WriteEndObject();
writer.Flush();
return sw.GetStringBuilder().ToString();
}
Y así serializaríamos un array:
writer.WriteStartArray();
writer.WriteValue("JSON!");
writer.WriteValue(1);
writer.WriteValue(true);
writer.WriteStartObject();
writer.WritePropertyName("property");
writer.WriteValue("value");
writer.WriteEndObject();
writer.WriteEndArray();
==== Links ====
* [[http://james.newtonking.com/archive/2006/06/26/Json.NET-_2D00_-Simplifying-.NET-_3C002D003E00_-JavaScript-communication.aspx|Artículo]]
* {{fw:othersnet:json131.zip|Versión para .NET 2.0}}