json.net with c sharp - c#

string jsondata = #"{""meta"":{""code"":200}}";
dynamic json = JsonConvert.DeserializeObject(jsondata);
I have above json data and I created class for it. I have also deserialized it - how can I iterate this json variable
public class Meta
{
public int code { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
}

To Work with your code, you should user the typed convert
string jsondata = #"{""meta"":{""code"":200}}";
Meta json = JsonConvert.DeserializeObject<Meta>(jsondata);
Then you can Acces all the members in the meta obj.
With normal .net json runtime you can deserialize a string
string jsondata = #"{""meta"":{""code"":200}}"
Meta meta = JsonHelper.JsonDeserialize<Meta>(jsondata);
For more info see http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
You need to have this code ofc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
/// <summary>
/// JSON Serialization and Deserialization Assistant Class
/// </summary>
public class JsonHelper
{
/// <summary>
/// JSON Serialization
/// </summary>
public static string JsonSerializer<T> (T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// <summary>
/// JSON Deserialization
/// </summary>
public static T JsonDeserialize<T> (string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}

Related

Serialize/deserialize without external library in c#

How do i serialize/de serialize JSON data in c# without using any library or nugget package
i tried this
it allways shows me error!
{
/// <summary>
/// Deserialize an from json string
/// </summary>
public static T Deserialize<T>(string body)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(body);
writer.Flush();
stream.Position = 0;
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
}
}
/// <summary>
/// Serialize an object to json
/// </summary>
public static string Serialize<T>(T item)
{
using (MemoryStream ms = new MemoryStream())
{
new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
return Encoding.Default.GetString(ms.ToArray());
}
}
}```
System.Text.Json as a library from Microsoft and Newtonsoft.Json, an external serializer friend.
Dotnet has a library for your request Source page
string jsonString = JsonSerializer.Serialize(weatherForecast);
var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Calling a method in C#

I have problem to call a method in a WCFService. I downladed the file below for a project and I want to call a method in SampleHttpResquestAndResponse class in my WCFService (Also, I tried to do it in a main method and i couldn't succeed it either). However I can't do it, i can't find the method when I type it. How to call those methods in SampleHttpResquestAndResponse class?
using System;
using System.IO;
using System.Net;
using System.Text;
using System.IO.Compression;
using System.Xml.Serialization;
namespace Sample
{
public class SampleHttpResquestAndResponse
{
/// <summary>
/// Adonis servisi ile iletişim kurmayı sağlar.
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="prm_ServiceName">string</param> SearchHotels // BasketHotels // ConfirmHotels
/// <param name="prm_Criteria">object</param>
/// <param name="prm_Url">string</param> "http://xmltest.adonis.com/AdonisServices"
/// <returns>T</returns>
public static T AdonisRequestResponseMethod<T>(string prm_ServiceName, object prm_Criteria, string prm_Url)
{
#region Variables
HttpWebRequest HttpWebRequest;
T ReturnValue;
#endregion
try
{
#region Xml Serializer
var XmlString = SampleHttpResquestAndResponse.ConvertTypeToXml<object>(prm_Criteria).ToString();
#endregion
#region Http Web Request
HttpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}?prm_CurrentData={2}", prm_Url, prm_ServiceName, XmlString));
HttpWebRequest.ContentType = "text/xml;charset=\"utf-8\"";
HttpWebRequest.Method = "POST";
HttpWebRequest.Timeout = 80000000;
#endregion
#region Http Web Response
StreamWriter StreamWriterPost = new StreamWriter(HttpWebRequest.GetRequestStream());
StreamWriterPost.Write(XmlString);
StreamWriterPost.Close();
HttpWebResponse HttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
StreamReader StreamReaderResponse = new StreamReader(HttpWebResponse.GetResponseStream(), Encoding.UTF8);
string StringResponse = string.Empty;
if (HttpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream decompress = new GZipStream(HttpWebResponse.GetResponseStream(), CompressionMode.Decompress))
{
StreamReader reader = new StreamReader(decompress);
StringResponse = reader.ReadToEnd();
}
}
else
{
StreamReader reader = new StreamReader(HttpWebResponse.GetResponseStream(), Encoding.UTF8);
StringResponse = reader.ReadToEnd();
}
#endregion
#region Return Value Type Process (DESERIALIZE)
ReturnValue = SampleHttpResquestAndResponse.ConvertXmlToType<T>(StringResponse.ToString()).Data;
#endregion
#region Return Value
return ReturnValue;
#endregion
}
catch (Exception ex)
{
#region Return Value
return ReturnValue = SampleHttpResquestAndResponse.ConvertXmlToType<T>(ex.Message).Data;
#endregion
}
}
public static ResultDTO<T> ConvertXmlToType<T>(string prm_Xml)
{
#region Variables
T ReturnValue;
#endregion
try
{
#region Replace String Value
prm_Xml = prm_Xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
, "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
prm_Xml = prm_Xml.Replace("<", "<").Replace(">", ">").Replace(""", "\"");
#endregion
#region Deserialize
using (MemoryStream MemoryStream = new MemoryStream())
{
using (StreamWriter StreamWriter = new StreamWriter(MemoryStream))
{
StreamWriter.Write(prm_Xml);
StreamWriter.Flush();
MemoryStream.Position = 0;
XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
using (StreamReader StreamReader = new StreamReader(MemoryStream))
{
StreamReader.ReadLine();
#region Result Value (SET)
ReturnValue = (T)XmlSerializer.Deserialize(StreamReader);
#endregion
}
}
}
#endregion
#region Return Value
return new ResultDTO<T>
{
Data = ReturnValue,
Success = true
};
#endregion
}
catch (Exception ex)
{
#region Return Value
return new ResultDTO<T>
{
Success = false,
Message = string.Format("Error Type : {0} Code : {1} Method Name : {2} Error Mesage : {3}", "Undetermined", "1000", "ConvertXmlToType", ex.Message),
};
#endregion
}
}
public static string ConvertTypeToXml<T>(T prm_Criteria)
{
#region Variables
XmlSerializer XmlSerializer;
StringWriter StringWriter = new StringWriter();
#endregion
try
{
#region Xml Serializer
XmlSerializer = new XmlSerializer(prm_Criteria.GetType());
XmlSerializer.Serialize(StringWriter, prm_Criteria);
var XmlString = StringWriter.ToString();
#endregion
#region Request Replace
return XmlString = XmlString.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
#endregion
}
catch (Exception ex)
{
throw ex;
}
finally
{
GC.SuppressFinalize(StringWriter);
}
}
}
public class ResultDTO
{
#region Properties
/// <summary>
/// İslem durumu.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// İşlem mesajı.
/// </summary>
public string Message { get; set; }
#endregion
}
public class ResultDTO<T> : ResultDTO
{
#region Fields
/// <summary>
/// Generic data tipi.
/// </summary>
private T data = Activator.CreateInstance<T>();
#endregion
#region Properties
/// <summary>
/// Generic data tipi
/// </summary>
public T Data
{
get
{
if (data == null)
return data = default(T);
return data;
}
set { data = value; }
}
#endregion
}
}
PS: I know it is a little bit silly question, but i couldn't figure it. If it is needed, the below is how i try to call any method in this class in a simple way
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.Net;
using System.Text;
using System.IO.Compression;
using System.Xml.Serialization;
using Sample;
namespace Adonis
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdonisService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select AdonisService.svc or AdonisService.svc.cs at the Solution Explorer and start debugging.
public class AdonisService : IAdonisService
{
ResultDTO res = new ResultDTO();
SampleHttpResquestAndResponse samp = new SampleHttpResquestAndResponse();
public string results()
{
string a1 = "";
object c = new object();
c = 434;
string b = "";
string a = "";
a= samp.AdonisRequestResponseMethod(a, c, b);
}
}
}
AdonisRequestResponseMethod is static, and as such would be called like this:
SampleHttpResquestAndResponse.AdonisRequestResponseMethod(a, b, c);
However, it is also a generic method, so you will have to supply the type you require:
SampleHttpResquestAndResponse.AdonisRequestResponseMethod<string>(a, b, c);
I see 2 things wrong here:
The method is both a generic method.
Since it's a generic method, you must provide a type for it:
SampleHttpResquestAndResponse samp = new SampleHttpResquestAndResponse ();
samp.AdonisRequestResponseMethod<SomeType>(a, b, c);
However, that's not the complete answer,
It's a static method, which means that you can't reference the method from an instance of the class, rather you must reference it from the class type
SampleHttpResquestAndResponse.AdonisRequestResponseMethod<SomeType>(a, b, c);
Oh, and one more thing... SampleHttpResquestAndResponse has an extra 's' in the 'Request' portion of the name. That might give you headaches later. Hope this helps!

Why XML has empty spaces instead data inside after serialization?

After serialization sometimes xml files is filled with empty spaces. Why is it happen?
My serialization code is:
XmlSerializer serializer = new XmlSerializer(typeof(SerializableStorage));
using (StreamWriter sw = new StreamWriter(storageName, false, myEncoding))
{
serializer.Serialize(sw, messages);
}
This code serializes me messages into XML.
SerializableStorage looks like:
[XmlRoot("Storage")]
public class SerializableStorage
{
/// <summary>
/// Gets or sets an array of server messages
/// </summary>
[XmlArray("Messages")]
[XmlArrayItem("Message")]
public List<NMessage> Messages
{
get;
protected set;
}
/// <summary>
/// Public constructor
/// </summary>
public SerializableStorage()
{
Messages = new List<NMessage>();
}
}
NMessage class has all fields as public.
And deserialization if needed:
XmlSerializer serializer = new XmlSerializer(typeof(SerializableStorage));
StreamReader reader = new StreamReader(storageName, myEncoding);
StoreMessages = (SerializableStorage)serializer.Deserialize(reader);
reader.Close();
I've attached an "empty xml" example here

Serialize and Deserialize object graph using BinaryFormatter

I'm trying to serialize my object graph to a string then deserialize it from a string. The object serializes just fine if I do this
using (var memStream = new System.IO.MemoryStream())
{
mf.Serialize(memStream, this);
memStream.Seek(0, 0);
Search s;
using (var memStrClone = new System.IO.MemoryStream())
{
memStream.CopyTo(memStrClone);
memStrClone.Seek(0, 0);
s = mf.Deserialize(memStrClone) as Search;
}
}
The above code works but serializing to a string and trying to deserialize that same string like this
Search s;
string xml = ToString<Search>(this);
s = FromString<Search>(xml);
public static TType FromString<TType>(string input)
{
var byteArray = Encoding.ASCII.GetBytes(input);
using (var stream = new MemoryStream(byteArray))
{
var bf = new BinaryFormatter();
return (TType)bf.Deserialize(stream);
}
}
public static string ToString<TType>(TType data)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, data);
return Encoding.ASCII.GetString(ms.GetBuffer());
}
}
Throws an exception
No assembly ID for object type '1936026741 Core.Sebring.BusinessObjects.Search.Search'.
Any help is greatly appreciated. Thanks.
Here is some code which will do what you want to to (I think) - but I've got to ask - why do you want to serialize to a string like that?
If the class is simple enough to serialise to a string, use an XML serializer which is much easier to deal with; if you want to serialize it out to disk, binary write it out to a file and if it is complicated and you are serializing it to transmit - consider using something like protobuf-net.
I think the crux of your problem is that you are trying to use ASCII encoding - I'm using Base64 encoding.
Anyway - here goes (I've just had a guess at your Search class!)
class Program
{
[Serializable]
public class Search
{
public Guid ID { get; private set; }
public Search() { }
public Search(Guid id)
{
ID = id;
}
public override string ToString()
{
return ID.ToString();
}
}
static void Main(string[] args)
{
Search search = new Search(Guid.NewGuid());
Console.WriteLine(search);
string serialized = SerializeTest.SerializeToString(search);
Search rehydrated = SerializeTest.DeSerializeFromString<Search>(serialized);
Console.WriteLine(rehydrated);
Console.ReadLine();
}
}
public class SerializeTest
{
public static Encoding _Encoding = Encoding.Unicode;
public static string SerializeToString(object obj)
{
byte[] byteArray = BinarySerializeObject(obj);
return Convert.ToBase64String(byteArray);
}
public static T DeSerializeFromString<T>(string input)
{
byte[] byteArray = Convert.FromBase64String(input);
return BinaryDeserializeObject<T>(byteArray);
}
/// <summary>
/// Takes a byte array and deserializes it back to its type of <see cref="T"/>
/// </summary>
/// <typeparam name="T">The Type to deserialize to</typeparam>
/// <param name="serializedType">The object as a byte array</param>
/// <returns>The deserialized type</returns>
public static T BinaryDeserializeObject<T>(byte[] serializedType)
{
if (serializedType == null)
throw new ArgumentNullException("serializedType");
if (serializedType.Length.Equals(0))
throw new ArgumentException("serializedType");
T deserializedObject;
using (MemoryStream memoryStream = new MemoryStream(serializedType))
{
BinaryFormatter deserializer = new BinaryFormatter();
deserializedObject = (T)deserializer.Deserialize(memoryStream);
}
return deserializedObject;
}
/// <summary>
/// Takes an object and serializes it into a byte array
/// </summary>
/// <param name="objectToSerialize">The object to serialize</param>
/// <returns>The object as a <see cref="byte"/> array</returns>
public static byte[] BinarySerializeObject(object objectToSerialize)
{
if (objectToSerialize == null)
throw new ArgumentNullException("objectToSerialize");
byte[] serializedObject;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, objectToSerialize);
serializedObject = stream.ToArray();
}
return serializedObject;
}
}
HTH

trying to serialize and deserialize entity object in c#

I am using two methods below to serialize/deserialize entity framework object (ver. 4.0).
I tried several ways to accomplish this, and had no luck. Serialization works fine. I get nice xml formatted string, but when I try to deserialize I get error in XML. How is that possible?
Thanks.
public static string SerializeObject(Object obj)
{
XmlSerializer ser = new XmlSerializer(obj.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
string xml = doc.InnerXml;
return xml;
}
public static object DeSerializeAnObject(string xml, Type objType)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(objType);
object obj = ser.Deserialize(reader);
return obj;
}
I use generic methods to serialize and deserialize:
/// <summary>
/// Serializes an object to Xml as a string.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="ToSerialize">Object of type T to be serialized.</param>
/// <returns>Xml string of serialized type T object.</returns>
public static string SerializeToXmlString<T>(T ToSerialize)
{
string xmlstream = String.Empty;
using (MemoryStream memstream = new MemoryStream())
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
XmlTextWriter xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);
xmlSerializer.Serialize(xmlWriter, ToSerialize);
xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
}
return xmlstream;
}
/// <summary>
/// Deserializes Xml string of type T.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="XmlString">Input Xml string from which to read.</param>
/// <returns>Returns rehydrated object of type T.</returns>
public static T DeserializeXmlString<T>(string XmlString)
{
T tempObject = default(T);
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlString)))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
tempObject = (T)xs.Deserialize(memoryStream);
}
return tempObject;
}
// Convert Array to String
public static String UTF8ByteArrayToString(Byte[] ArrBytes)
{ return new UTF8Encoding().GetString(ArrBytes); }
// Convert String to Array
public static Byte[] StringToUTF8ByteArray(String XmlString)
{ return new UTF8Encoding().GetBytes(XmlString); }
i THINK the issue is with this line:
string xml = doc.InnerXml;
you want ALL the xml, not just the xml inside the root node.
Just return sb.ToString(), loading into the XmlDocument is not doing anything.
Some redundancies and usings was excluded. Refactored and cleaned up:
namespace MyProject
{
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public static class Serializer
{
#region Public Methods and Operators
/// <summary>
/// Deserializes Xml string of type T.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="XmlString">Input Xml string from which to read.</param>
/// <returns>Returns rehydrated object of type T.</returns>
public static T DeserializeXmlString<T>(string xmlString)
{
T tempObject;
using (var memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlString)))
{
var xs = new XmlSerializer(typeof(T));
tempObject = (T)xs.Deserialize(memoryStream);
}
return tempObject;
}
/// <summary>
/// Serializes an object to Xml as a string.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="toSerialize">Object of type T to be serialized.</param>
/// <returns>Xml string of serialized type T object.</returns>
public static string SerializeToXmlString<T>(T toSerialize)
{
string xmlstream;
using (var memstream = new MemoryStream())
{
var xmlSerializer = new XmlSerializer(typeof(T));
var xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);
xmlSerializer.Serialize(xmlWriter, toSerialize);
xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
}
return xmlstream;
}
#endregion
#region Methods
private static byte[] StringToUTF8ByteArray(string xmlString)
{
return new UTF8Encoding().GetBytes(xmlString);
}
private static string UTF8ByteArrayToString(byte[] arrBytes)
{
return new UTF8Encoding().GetString(arrBytes);
}
#endregion
}
}

Categories