Created
January 9, 2012 21:22
-
-
Save danielwertheim/1585003 to your computer and use it in GitHub Desktop.
ServiceStack struct fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Content2 is represented as name in the Json, event if it's ToString returns null. Tried SerializeFn to. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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