问题描述
我在C#中,它包装一个GUID的结构。我使用DataContractJsonSerializer序列化包含类的实例对象。当我是直接使用GUID,它是序列化作为一个普通的字符串,但现在它的序列化为一个名称/值对。这里有一个NUnit测试和支持code演示该问题:
I have a struct in C# that wraps a guid. I'm using DataContractJsonSerializer to serialize an object containing an instance of that class. When I was using a guid directly, it was serialized as a plain string, but now it's serialized as a name/value pair. Here's an NUnit test and supporting code that demonstrates the problem:
private static string ToJson<T>(T data)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (T));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, data);
return Encoding.Default.GetString(ms.ToArray());
}
}
[Serializable]
private class ID
{
private Guid _value;
public static explicit operator ID(Guid id)
{
return new ID { _value = id };
}
public static explicit operator Guid(ID id)
{
return id._value;
}
}
[Test]
public void IDShouldSerializeLikeGuid()
{
Guid guid = Guid.NewGuid();
ID id = (ID) guid;
Assert.That(ToJson(id), Is.EqualTo(ToJson(guid)));
}
和测试运行的输出:
NUnit.Framework.AssertionException: Expected string length 38 but was 49. Strings differ at index 0.
Expected: ""7511fb9f-3515-4e95-9a04-06580753527d""
But was: "{"_value":"7511fb9f-3515-4e95-9a04-06580753527d"}"
-----------^
如何序列化我的结构作为一个普通的字符串,让我测试过?
How do I serialize my struct as a plain string and make my test pass?
推荐答案
在这种情况下,它看起来像你真的不希望JSON,你想要一个字符串,再presentation。在这种情况下,我会创建这样一个接口:
In this case it looks like you don't really want JSON, you want a string representation. In that case I would create an interface like this:
interface IStringSerialized
{
String GetString();
}
实现你的 ID
键入此接口(和所有其他类型的有类似的要求)。
Implement this interface on your ID
type (and all other types that have similar requirements).
[Serializable]
class ID : IStringSerialized
{
private Guid _value;
public static explicit operator ID(Guid id)
{
return new ID { _value = id };
}
public static explicit operator Guid(ID id)
{
return id._value;
}
public string GetString()
{
return this._value.ToString();
}
}
然后修改您的序列化的方法来处理这些特殊情况:
Then modify your serialization method to handle these special cases:
private static string ToJson<T>(T data)
{
IStringSerialized s = data as IStringSerialized;
if (s != null)
return s.GetString();
DataContractJsonSerializer serializer
= new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, data);
return Encoding.Default.GetString(ms.ToArray());
}
}
这篇关于我怎样才能让DataContractJsonSerializer序列化一个对象作为一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!