日期:2014-05-20  浏览次数:20703 次

请问一下有谁知道把model怎么序列化成JSON格式的string啊?
1.
// 根据对象序列化
public static string Serialize<T>(object obj)
{
//预定义
string result = null;
//尝试序列化
try
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
result = Encoding.UTF8.GetString(dataBytes);
}
catch
{
//失败
}
return result;
}

2.model层

namespace iTry86.Quote.Model
{

  [Serializable]
  public class stocksnap
  {
  [DataMember(Order = 0)]
  ///<summary>
  ///股票代码
  ///</summary>
  public string Code { get;set;}

  [DataMember(Order = 1)]
  ///<summary>
  ///股票名称
  ///</summary>
  public string Name { get;set;}

  [DataMember(Order = 2)]
  ///<summary>
  ///收盘价
  ///</summary>
  public float Close { get;set;}

  [DataMember(Order = 3)]
  ///<summary>
  ///开盘价
  ///</summary>
  public float Open { get;set;}

  [DataMember(Order = 4)]
  ///<summary>
  ///最高价
  ///</summary>
  public float High { get;set;}
}}

3.webservice里面的方法

  [WebMethod]
  public string Add(string input)
  {


  iTry86.Quote.Model.stocksnap stock = new iTry86.Quote.Model.stocksnap();
  stock.Code=values[0].Trim();
  stock.Name= values[1].Trim();
  stock.Close= float.Parse(values[2].Trim());
  stock.Open= float.Parse(values[3].Trim());
  stock.High= float.Parse(values[4].Trim());



string strjson = BingLib.DataAccess.Json.Serialize<string>(stock);//序列化成string

  return strjson;
  }


请问上面哪里有错误?怎么不能进行序列化?
结果应该是json格式的字符串,但是输出的结果却是
  <?xml version="1.0" encoding="utf-8" ?> 
  <string xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:nil="true" xmlns="http://www.itry86.com/" /> 
这是怎么回事?

------解决方案--------------------
model的 [Serializable] 上面添加
[DataContract(Namespace = "http://www.itry86.com")]

//将对象转化成Json字符串

DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(iTry86.Quote.Model.SH_Ticks));
string strjson = string.Empty;
using (MemoryStream ms = new MemoryStream())
{

ds.WriteObject(ms, ticks);

strjson = System.Text.Encoding.UTF8.GetString(ms.ToArray());

}