DataContractJsonSerializer cannot deserialize Newtonsoft JsonSerializer - c#

What do first 3 bytes written by JsonSerializer on the begging of stream mean and why does DataContractJsonSerializer have a problem with them?
Sample:
Foo foo = new Foo();
using (MemoryStream stream = new MemoryStream())
{
//serialize using JsonSerializer
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, 4096, true))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
JsonSerializer jsonSerializer = JsonSerializer.Create();
jsonSerializer.Serialize(jsonWriter, foo, typeof(Foo));
}
// reset position
stream.Seek(0, SeekOrigin.Begin);
// deserialize using DataContractJsonSerializer
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(stream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Foo));
foo = (Foo)dataContractJsonSerializer.ReadObject(jsonReader);
}
}
Deserialization ends up with exception: Additional information: There was an error deserializing the object of type Sandbox.Program+Foo. Encountered unexpected character 'ï'.

Related

JsonSerializer size limited to 7168 chars/bytes?

Consider this sample code:
var ms = new MemoryStream();
using (StreamWriter sw = new StreamWriter(ms))
using (JsonWriter writer = new JsonTextWriter(sw))
{
this.GetSerializer().Serialize(writer, data, typeof(T));
// convert stream to string
ms.Position = 0;
var reader = new StreamReader(ms);
var textToSend = reader.ReadToEnd();
}
Serializer obtained from this method:
private JsonSerializer GetSerializer()
{
var serializer = new JsonSerializer
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
serializer.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd\\THH:mm:ss.fffZ" });
return serializer;
}
When I serialize 'data' it produces memory stream with 7168 bytes and when I convert to string I see how message being truncated. Searched but can't find what might be causing this limit?

Round trip XML serializing with .Net DataContractSerializer fails

I seem to be getting some junk at the head of my serialized XML string. I have a simple extension method
public static string ToXML(this object This)
{
DataContractSerializer ser = new DataContractSerializer(This.GetType());
var settings = new XmlWriterSettings { Indent = true };
using (MemoryStream ms = new MemoryStream())
using (var w = XmlWriter.Create(ms, settings))
{
ser.WriteObject(w, This);
w.Flush();
return UTF8Encoding.Default.GetString(ms.ToArray());
}
}
and when I apply it to my object I get the string
<?xml version="1.0" encoding="utf-8"?>
<RootModelType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WeinCad.Data">
<MoineauPump xmlns:d2p1="http://schemas.datacontract.org/2004/07/Weingartner.Numerics">
<d2p1:Rotor>
<d2p1:Equidistance>0.0025</d2p1:Equidistance>
<d2p1:Lobes>2</d2p1:Lobes>
<d2p1:MajorRadius>0.04</d2p1:MajorRadius>
<d2p1:MinorRadius>0.03</d2p1:MinorRadius>
</d2p1:Rotor>
</MoineauPump>
</RootModelType>
Note the junk at the beginning. When I try to deserialize this
I get an error. If I copy paste the XML into my source minus
the junk prefix I can deserialize it. What is the junk text
and how can I remove it or handle it?
Note my deserialization code is
public static RootModelType Load(Stream data)
{
DataContractSerializer ser = new DataContractSerializer(typeof(RootModelType));
return (RootModelType)ser.ReadObject(data);
}
public static RootModelType Load(string data)
{
using(var stream = new MemoryStream(Encoding.UTF8.GetBytes(data))){
return Load(stream);
}
}
This fix seems to work
public static string ToXML(this object obj)
{
var settings = new XmlWriterSettings { Indent = true };
using (MemoryStream memoryStream = new MemoryStream())
using (StreamReader reader = new StreamReader(memoryStream))
using(XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
DataContractSerializer serializer =
new DataContractSerializer(obj.GetType());
serializer.WriteObject(writer, obj);
writer.Flush();
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}

Converting code to use JSON.net instead of System.Runtime.Serialization.DataContractSerializer

How do I do the equivalent in JSON.net?
public SerializedResults SerializeResults(Type queryType, IEnumerable entities)
{
var results = SerializeDynamicType(queryType);
var objList = AnonymousFns.DeconstructMany(entities, false, queryType).ToList();
var ms = new MemoryStream();
var type = objList.GetType();
var serializer = new DataContractSerializer(type);
using (ms)
{
using (GZipStream compress = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
{
serializer.WriteObject(compress, objList);
}
}
results.ByteArray = ms.ToArray();
return results;
}
I am confused with this line in particular:
var serializer = new DataContractSerializer(type);
How do you do that in JSON.NET??
THANKS :-)
With JSON.NET, you don't need the type when serializing. I'm assuming that it works out the type you are passing in on its own.
So, you can get rid of this completely:
var type = objList.GetType();
var serializer = new DataContractSerializer(type);
And change this:
serializer.WriteObject(compress, objList);
To:
var json = JsonConvert.SerializeObject(objList);
Here are the JSON.Net docs for JsonConvert.
I believe you can use the BsonWriter to write to a stream. I'm not sure it will give you the exact same binary format you had before, but in concept it is the same.
public SerializedResults SerializeResults(Type queryType, IEnumerable entities)
{
var results = SerializeDynamicType(queryType);
var objList = AnonymousFns.DeconstructMany(entities, false, queryType).ToList();
var ms = new MemoryStream();
using (ms)
{
using (GZipStream compress = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
{
using( BsonWriter writer = new BsonWriter(compress))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, objList);
}
}
}
results.ByteArray = ms.ToArray();
return results;
}

Assign textwriter to memory writer

I am writing an xml file but am missing some value for specific field. I check that when the object comes which contains the value that specific value exist, but after writing the xml the value doesn't exist.
This is the code that I use, I think XmlTextWriter could be the cause of the wrong xml.
There is another method which could be used for it, that is TextWriter but it failed to convert into memorystream.
string xmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
// XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);
TextWriter xmlTextWriter=new StreamWriter(memoryStream,Encoding.ASCII);
xs.Serialize(xmlTextWriter, obj);
memoryStream =(MemoryStream)xmlTextWriter.
//(MemoryStream)xmlTextWriter.BaseStream;
xmlString = ASCIIByteArrayToString(memoryStream.ToArray());
return `xmlString;`
Any idea how I can know why and where the problem occurs.
I think you are over-complicating it with the memory stream. You can serialize to a StringWriter (which derives from TextWriter) then call ToString() if you want to get the XML string.
XmlSerializer xs = new XmlSerializer(typeof(T));
StringWriter sw = new StringWriter();
xs.Serialize(sw, obj);
return sw.ToString();
Try disposing properly your IDisposable resources by wrapping them in using statements:
public string SerializeToXml<T>(T obj)
{
using (var stream = new MemoryStream())
{
var xs = new XmlSerializer(typeof(T));
xs.Serialize(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}

ReportDocument serialization

I want to serialize a ReportDocument using XML serialization but in vain, that's my code:
public String serialiser (ReportDocument rd)
{
StringWriter sw= new StringWriter();
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ReportDocument));
xs.Serialize(sw, rd);
return sw.ToString();
}
NB: CrystalDecisions.CrystalReports.Engine.ReportDocument.
I got the following error:
An error occurred during the reflection of the type 'CrystalDecisions.CrystalReports.Engine.ReportDocument'.
How could I serialize it?!
My guess is that type is not marked as serializable. Have you tried doing binary serialization?
public static byte[] SerializeToBytes<T>(T original)
{
byte[] results;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, original);
stream.Seek(0, SeekOrigin.Begin);
results = stream.ToArray();
}
return results;
}

Categories

Resources