JSON Conversions
The following methods illustrate how to perform conversions with JSON objects and other sources.Convert a JSON String to a JSON Object
public object ConvertJsonStringToObject(string jsonString, Type type)
{
// declare the return variable
object objRV = null;
using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(mem))
{
// write our string to the memory stream.
sw.Write(jsonString);
sw.Flush();
// make sure the memory stream position is set at the beginning.
mem.Position = 0;
// make the call to convert our stream to the object.
objRV = this.ConvertJsonStreamToObject(mem, type);
}
return objRV;
}
Convert a Stream Containing JSON Information to a JSON Object
internal object ConvertJsonStreamToObject(System.IO.Stream strm, Type type)
{
// declare the return variable
object objRV = null;
//Create a serializer to do the JSON work for us
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
// read the stream and write it to our object.
objRV = ser.ReadObject(strm);
return objRV;
}
internal string ConvertJsonObjectToString(object jsonObject)
{
string sRV = null;
if (jsonObject != null)
{
StringBuilder sbOutput = new StringBuilder();
this.ConvertJsonObjectToString(jsonObject, sbOutput);
if (sbOutput.Length > 0)
{
sRV = sbOutput.ToString();
}
}
return sRV;
}
internal void ConvertJsonObjectToString(object jsonObject, StringBuilder sbOutput)
{
//Create a serializer to do the JSON work for us
DataContractJsonSerializer ser = new DataContractJsonSerializer(jsonObject.GetType());
using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
using (System.IO.StreamReader sr = new System.IO.StreamReader(mem))
{
// write the object to the memory stream.
ser.WriteObject(mem, jsonObject);
// flush the stream
mem.Flush();
// move the pointer to the beginning
mem.Position = 0;
sbOutput.Append(sr.ReadToEnd());
}
}
internal void WriteJsonObjectToStream(object jsonObject, System.IO.Stream strm)
{
//Create a serializer to do the JSON work for us
DataContractJsonSerializer ser = new DataContractJsonSerializer(jsonObject.GetType());
// write the object to the stream.
ser.WriteObject(strm, jsonObject);
}
Last modified by Mohit @ 4/8/2025 9:27:52 AM