#
JSON Serialization
h5 offers multiple ways to handle JSON data serialization and deserialization.
#
1. Native JSON
You can use the browser's native JSON.parse and JSON.stringify methods directly, either via Script.Write or Global.JSON.
using H5;
public static void Serialize(object obj)
{
var json = Global.JSON.Stringify(obj);
Console.WriteLine(json);
}
public static void Deserialize(string json)
{
var obj = Global.JSON.Parse(json);
Console.WriteLine(obj);
}
This is lightweight but doesn't handle complex .NET types (like DateTime, Guid, or custom classes) correctly out-of-the-box unless they are simple DTOs.
#
2. Object Literals
For simple data transfer objects (DTOs) that map directly to JavaScript objects, you can use the [ObjectLiteral] attribute. This instructs the compiler to treat instances of the class as plain JavaScript objects ({}) rather than full class instances with prototype chains.
[ObjectLiteral]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var p = new Person { Name = "Alice", Age = 30 };
// Compiled to: var p = { Name: "Alice", Age: 30 };
This is extremely efficient for JSON serialization as JSON.stringify(p) works perfectly.
#
3. h5.Newtonsoft.Json
For full-featured JSON serialization compatible with Newtonsoft.Json (Json.NET), use the h5.Newtonsoft.Json package.
#
Installation
dotnet add package h5.Newtonsoft.Json
#
Usage
The API mirrors the standard Newtonsoft.Json API.
using Newtonsoft.Json;
public class User
{
public string Name { get; set; }
[JsonProperty("user_age")]
public int Age { get; set; }
}
var user = new User { Name = "Bob", Age = 25 };
string json = JsonConvert.SerializeObject(user);
// Output: {"Name":"Bob","user_age":25}
var user2 = JsonConvert.DeserializeObject<User>(json);
This supports:
- Custom property names (
[JsonProperty]) - Ignoring properties (
[JsonIgnore]) - Handling complex types (
DateTime,Guid,TimeSpan) - Polymorphic deserialization (
TypeNameHandling) - Custom converters (
JsonConverter)
This is the recommended approach for robust applications.