Json Serializer for .netcore ant .Net3.5 - c#

Is there any json serializer library that work in .netcore and .Net3.5?
I need to use a library in a multiplatform project the problem is that Newtonsoft's library works only in .Net Framework and System.Text.Json only works in .netcore.
** I tried Json.Net but no luck. I get this kind of error on all of the libraries:

You can use DataContractJsonSerializer
I am using it in my .net standard library to serialize and de-serialize my model objects to json.
public static string PrepareJsonString<T>(object objectToBeParsed)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
string json = string.Empty;
using (var ms = new MemoryStream())
{
dataContractSerializer.WriteObject(ms, (T)objectToBeParsed);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
json = sr.ReadToEnd();
}
return json;
}
public static object PrepareObjectFromString<T>(string json)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var deSerializedUser = dataContractSerializer.ReadObject(memoryStream);
return deSerializedUser;
}
}
sample to consume this functions
List<MyModel> list= PrepareObjectFromString<List<MyModel>>(myJson);
or
MyModel list= PrepareObjectFromString<MyModel>(myJson);
string json=PrepareJsonString<MyModel>(myModelInstance);
Hope this helps.
Thank you.

Related

Serialize object in UWP app

I'm trying to pass an object over a StreamSocket, so i need to serialize it before i can do that.
I looked at the BinaryFormatter, but that doesn't seem to be available in UWP?
Any suggestions on how to serialize an object, and preferably in the most compact way.
You can serialize your own .NET objects; JSON.NET is a very popular choice, but the built-in DataContractSerializer should also work if you don't want any dependencies.
You cannot serialize any WinRT objects.
If you want to serialize an object to json, at first you have to add Newtonsoft.Json to your project.
To install Json.NET, run the following command in the Package Manager Console:
PM> Install-Package Newtonsoft.Json
Then use this code to pass your object :
(Note: In this sample I suppose your server and client are the same and the port that you are using is: 1800.)
try
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName("127.0.0.1");
string serverPort = "1800";
socket.ConnectAsync(serverHost, serverPort);
var json = JsonConvert.SerializeObject(object);
byte[] buffer = Encoding.UTF8.GetBytes(json);
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
var request = json;
writer.WriteLine(request);
writer.Flush();
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = reader.ReadLine();
}
catch (Exception e)
{
var err = e.Message;
//Handle exception here.
}
Inform me if you have any other question.

Newtonsoft.Json - Out of memory exception while deserializing big object

I have a problem deserializing a JSON file of about 1GB. When I run the following code I get an out of memory exception:
using (FileStream sr = new FileStream("myFile.json", FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(sr))
{
using (JsonReader jsReader = new JsonTextReader(reader))
{
JsonSerializer serializer = new JsonSerializer();
dataObject = serializer.Deserialize<T>(jsReader);
}
}
}
the exception is thrown by
Newtonsoft.Json.Linq.JTokenWriter.WriteValue(Int64 value)
The serialization works well, here is the code I'm using
using (StreamWriter reader = new StreamWriter("myFile.json"))
{
using (JsonReader jsWriter = new JsonWriter(reader))
{
JsonTextWriter jsonWriter = new JsonTextWriter(jsWriter) { Formatting = Formatting.Indented };
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, dataObject, dataObject.GetType());
jsonWriter.Flush();
}
}}
Am I doing something wrong in the deserialization? Can you help suggesting a way to deserialize big json object?
Thanks
According to Newtonsoft.Json Performance Tips your approach has to work (because you read via stream and it should make portion from your file). I can't figure out why your code doesn't work.
But you can try another approach, that was described in the next article - Parsing Big Records with Json.NET

How to serialize/deserialize a C# WCF DataContract to/from XML

I am developing a WCF service which will be consumed by multiple different client applications. In order to make one functionality work, the server needs to read an XML file into a C# DataContract which is then passed on to the concerned client. As far as I understand from the MSDN website, this is possible but I couldn't find any complete examples. In particular, the website talks about a 'stream' parameter which I don't quite get yet.
My data contract has one property field which is a list of another data contract which has multiple simple property fields.
e.g.
[DataContract]
public class MyClass1 {
[DataMember]
public string name;
[DataMember]
public int age;
}
[DataContract]
public class MyClass2 {
[DataMember]
public List<MyClass1> myClass1List;
}
My classes look something like this.
Here is an example
MyClass1 obj = new MyClass1();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass1));
using (Stream stream = new FileStream(#"C:\tmp\file.xml", FileMode.Create, FileAccess.Write))
{
using (XmlDictionaryWriter writer =
XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
writer.WriteStartDocument();
dcs.WriteObject(writer, obj);
}
}
Books b = new Books();
DataContractSerializer dcs = new DataContractSerializer(typeof(Books));
try
{
Stream fs = new FileStream(#"C:\Users\temelm\Desktop\XmlFile.xml", FileMode.Create, FileAccess.Write);
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);
xdw.WriteStartDocument();
dcs.WriteObject(xdw, b);
xdw.Close();
fs.Flush();
fs.Close();
}
catch (Exception e)
{
s += e.Message + "\n";
}
This can be useful for you. When you need XElement. For instance when you going append node to XDocument or replece XElement of this document.
private XElement objectToXElement(SomeContractType obj)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(SomeContractType);
var ms = new MemoryStream();
var xw = XmlWriter.Create(ms);
dcs.WriteObject(xw, obj);
xw.Flush();
xw.Close();
ms.Position = 0;
XElement xe = XElement.Load(ms);
return xe;
}
There is the NetDataContractSerializer which solves a whole bunch of problems when using WCF.
See here MSDN NetDataContractSerializer
It is typically used for wrapping all kinds of objects and pass it over WCF.
You can use it for wrapping objects into a byte[] and transport it over WCF,
on the serverside, you can easily Deserialize the objects and do whatever
you want with them.
Here is a discussion on how to use this Serializer correctly:
MSDN Social
Code snippets are provided there also!

Using JSON in .Net

What libraries are available to handle JSON in .Net? I've seen this: http://james.newtonking.com/projects/json-net.aspx but would prefer a native library, if possible.
I have been using the JavaScriptSerializer some to expose data structures from a WCF service to Ajax calls, and it has been working out quite well.
The JavaScriptSerializer has been marked as obsolete in .NET 3.5 and but you could use the DataContractJsonSerializer.
EDIT: See this question on SO about whether JavaScriptSerializer is actually obsolete going forward in the .NET BCL. It looks like JavaScriptSerializer is no longer obsolete in .NET 3.5 SP1 - so it's probably fine to use that. If in doubt, you can use the contract serializer from WCF, or JSON.NET (if you're willing to include 3rd party code).
Here's some wrapper code to make using DataContractJsonSerializer nicer.
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
public class JSONHelper
{
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(obj.GetType());
using( MemoryStream ms = new MemoryStream() )
{
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
return retVal;
}
}
public static T Deserialize<T>(string json)
{
using( MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)) )
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
}
The code above is courtesy of: http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx,
I have altered it from it's original form to use best practices for object disposal (the using pattern .NET supports).
If you can require .Net 3.5, use System.Web.Script.Serialization.JavaScriptSerializer

Do I really need to write this "SerializationHelper"?

I just wrote this SerializationHelper class, but I can't believe this is necessary!
using System.IO;
using System.Xml.Serialization;
public static class SerializationHelper
{
public static string Serialize<T>(T obj)
{
var outStream = new StringWriter();
var ser = new XmlSerializer(typeof(T));
ser.Serialize(outStream, obj);
return outStream.ToString();
}
public static T Deserialize<T>(string serialized)
{
var inStream = new StringReader(serialized);
var ser = new XmlSerializer(typeof(T));
return (T)ser.Deserialize(inStream);
}
}
And it's used like this:
var serialized = SerializationHelper.Serialize(myObj);
and:
var myObj = SerializationHelper.Deserialize<MyType>(serialized)
Am I missing something in the .NET framework? This is not rocket science!
In actual fact, the bits where you call the .NET API are these:
var ser = new XmlSerializer(typeof(T));
ser.Serialize(outStream, obj);
var ser = new XmlSerializer(typeof(T));
var obj = (T) ser.Deserialize(inStream);
The rest of the code is your personal specialisation. I don't think that two lines of code is too much for calling an API. You could always condense them, e.g.
(new XmlSerializer(typeof(T))).Serialize(outStream, obj);
var obj = (T) (new XmlSerializer(typeof(T))).Deserialize(inStream);
Purely as an aside, I should point out that I regard storing XML data in string variables as a Code Smell. As soon as you take XML data out of its raw binary form (XDocument, XmlDocument, XPathDocument or any other type of DOM), you run up against encoding issues. What if a developer serialises an object to a string with encoding X, then writes the string to a disk file with encoding Y? Not very safe. Besides which, if encoding X is not UTF-16, how would you even represent the data in a .NET string?
It's useful if you are doing any real amount (>1) of serialization/deserialization within a project. This was the case for me one time, so I just put a similar class in a Utils library, along with other reusable functions.

Categories

Resources