c# - How can I make DataContractJsonSerializer serialize an object as a string? -
I have a straight in C #, which wraps up a grid. I am using the DataContractJsonSerializer to sort the object that contains the frequency of that class. When I was directly using a guide, it was sorted as a plain string, but now it is sorted in the form of a name / value pair here, there is a NUnit test and support code that shows the problem:
Private Static String ToJson & lt; T & gt; (T data) {DataContractJsonSerializer serializer = New data editing JSONSerializer (typeof (T)); (MemoryStream MS = New MemoryStream ()) Using {serializer.WriteObject (MS, Data); Return encoding. Default.GetString (MS. Toure ()); }} [Serialable] Private class ID {Private Gide _ value; Return Public Static Clear Operator ID (Guide ID) {new id {_value = id}; } Public static clear operator Gid {ID} {return id._value; }} [Test] Public Zero IDShouldSerializeLikeGuid () {guide guid = Guid.NewGuid (); ID ID = (ID) guide; Notice. That (ToJson (id), Is.EqualTo (ToJson (guid)); }
and test runner output:
NUnit.Framework.AssertionException: expected string length was 38 but 49. The strings are different in the 0 index. Expected: "" 7511fb9f-3515-4e95-9a04-06580753527d "" but was: "{" _value ":" 7511fb9f-3515-4e95-9a04-06580753527d "}" ----------- ^ < / Code>
How can I serialize my strat as a plain string and pass my exam?
In this case it seems that you do not really want JSON, you want to represent a string Are there. In that case I will create an interface like this:
Interface activating {string GetString (); }
Apply this interface to your id
type (and all other types of needs as well)
[serializable] Class ID: Iterating Serialized {Private Gide _ value; Return Public Static Clear Operator ID (Guide ID) {new id {_value = id}; } Public static clear operator Gid {ID} {return id._value; } Public String GetString () {return._value.ToString (); }}
Then modify your own serialization method to handle these special cases:
Private Static String ToJson & lt; T & gt; (T data) {IStringSerialized s = IStringSerialized as data; If (s! = Null) returns s.GetString (); Data ContractJason Serializer Serializer = New Data Contracts Surgery (Typef (T)); (MemoryStream MS = New MemoryStream ()) Using {serializer.WriteObject (MS, Data); Return encoding. Default.GetString (MS. Toure ()); }}
Comments
Post a Comment