C# 如何让 DataContractJsonSerializer 将对象序列化为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1178255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make DataContractJsonSerializer serialize an object as a string?
提问by Brian Victor
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:
我在 C# 中有一个包装 guid 的结构。我正在使用 DataContractJsonSerializer 来序列化包含该类实例的对象。当我直接使用 guid 时,它被序列化为一个普通字符串,但现在它被序列化为一个名称/值对。这是演示问题的 NUnit 测试和支持代码:
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)));
}
And the test runner output:
和测试运行器输出:
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?
如何将我的结构序列化为纯字符串并使我的测试通过?
回答by Andrew Hare
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:
在这种情况下,您似乎并不真正想要 JSON,而是想要一个字符串表示。在这种情况下,我会创建一个这样的界面:
interface IStringSerialized
{
String GetString();
}
Implement this interface on your ID
type (and all other types that have similar requirements).
在您的ID
类型(以及具有类似要求的所有其他类型)上实现此接口。
[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());
}
}
回答by David d C e Freitas
Try using the JavaScriptSerializerClass it will prevent the key, value bloat issue.
尝试使用JavaScriptSerializer类,它将防止键值膨胀问题。