Skip to content

Instantly share code, notes, and snippets.

@danielwertheim
Created January 9, 2012 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielwertheim/1585003 to your computer and use it in GitHub Desktop.
Save danielwertheim/1585003 to your computer and use it in GitHub Desktop.
ServiceStack struct fun
Content2 is represented as name in the Json, event if it's ToString returns null. Tried SerializeFn to.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var s = new Foo();
s.Content1 = "My content";
s.Name = "My name";
var json = ServiceStack.Text.JsonSerializer.SerializeToString(s, s.GetType());
Console.WriteLine(json);
var c = ServiceStack.Text.JsonSerializer.DeserializeFromString<Foo>(json);
Console.WriteLine(c.Name);
Console.WriteLine(c.Content1);
Console.WriteLine(c.Content2);
Console.ReadKey();
}
}
[Serializable]
public class Foo
{
public string Name { get; set; }
public Text Content1 { get; set; }
public Text Content2 { get; set; }
}
public interface IText { }
[Serializable]
public struct Text
{
private readonly string _value;
public Text(string value)
{
_value = value;
}
public static Text Parse(string value)
{
return value == null ? null : new Text(value);
}
public static implicit operator Text(string value)
{
return new Text(value);
}
public static implicit operator string (Text item)
{
return item._value;
}
public override string ToString()
{
return _value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment