El formato que mencionas es de hecho el "correcto". Pero también puede admitir otros formatos mediante el uso de un JsonConverter
personalizado: consulte el siguiente código para ver un ejemplo.
public class StackOverflow_10063118
{
public class Foo
{
public Guid guid;
public int i;
public override string ToString()
{
return string.Format("Foo[i={0},guid={1}]", i, guid);
}
}
class GuidConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Guid) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Null:
return Guid.Empty;
case JsonToken.String:
string str = reader.Value as string;
if (string.IsNullOrEmpty(str))
{
return Guid.Empty;
}
else
{
return new Guid(str);
}
default:
throw new ArgumentException("Invalid token type");
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (Guid.Empty.Equals(value))
{
writer.WriteValue("");
}
else
{
writer.WriteValue((Guid)value);
}
}
}
public static void Test()
{
Foo foo = new Foo { guid = Guid.Empty, i = 123 };
JsonSerializer js = new JsonSerializer();
js.Converters.Add(new GuidConverter());
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
js.Serialize(sw, foo);
Console.WriteLine(sb.ToString());
StringReader sr = new StringReader(sb.ToString());
Foo foo2 = js.Deserialize(sr, typeof(Foo)) as Foo;
Console.WriteLine(foo2);
}
}
FYI ReSharper da una [ "método impuro ..." advertencia] (http://stackoverflow.com/questions/9927434/impure-method-is-called-for-readonly-field) en 'Guid .Empty.Equals (value) ' – drzaus