protected void FormatOutgoingMessage<T>(T graph, string format)
{
if (format == null)
{
format = "json";
}
bool flag = format.ToUpper() == "XML";
WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers;
string s = string.Empty;
string str2 = headers.Get("Accept");
if (str2 != null)
{
bool flag2 = str2.ToLower().Contains("application/json");
if ((format.ToUpper() == "JSON") || (flag2 && !flag))
{
s = Utility.ToJson<T>(graph);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(s);
}
else
{
s = Utility.SerializeDataContract<T>(graph);
HttpContext.Current.Response.ContentType = "application/xml";
HttpContext.Current.Response.Write(s);
}
}
else
{
s = Utility.SerializeDataContract<T>(graph);
HttpContext.Current.Response.ContentType = "application/xml";
HttpContext.Current.Response.Write(s);
}
}
public static string ToJson<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
return Encoding.Default.GetString(stream.ToArray());
}
public static string SerializeDataContract<T>(T graph)
{
return Serialize<T>(graph, Encoding.UTF8);
}
{
if (format == null)
{
format = "json";
}
bool flag = format.ToUpper() == "XML";
WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers;
string s = string.Empty;
string str2 = headers.Get("Accept");
if (str2 != null)
{
bool flag2 = str2.ToLower().Contains("application/json");
if ((format.ToUpper() == "JSON") || (flag2 && !flag))
{
s = Utility.ToJson<T>(graph);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(s);
}
else
{
s = Utility.SerializeDataContract<T>(graph);
HttpContext.Current.Response.ContentType = "application/xml";
HttpContext.Current.Response.Write(s);
}
}
else
{
s = Utility.SerializeDataContract<T>(graph);
HttpContext.Current.Response.ContentType = "application/xml";
HttpContext.Current.Response.Write(s);
}
}
public static string ToJson<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
return Encoding.Default.GetString(stream.ToArray());
}
public static string SerializeDataContract<T>(T graph)
{
return Serialize<T>(graph, Encoding.UTF8);
}
No comments:
Post a Comment