JSON反序列化


/// <summary>

/// JSON反序列化

/// </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;

}

// List<shopMode> obj = util.HttpWeb.DeserializeFromJson<List<shopMode>>(r);
/// <summary>
/// JSON反序列化集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T DeserializeFromJson<T>(string jsonString) where T : class
{
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
T obj = (T)ds.ReadObject(ms);
return obj;
}
}

 

var json = "[{\"protype_id\":14,\"bellType\":0,\"tech_number\":7722},{\"protype_id\":14,\"bellType\":0,\"tech_number\":4272},{\"protype_id\":12,\"bellType\":0,\"tech_number\":3225},{\"protype_id\":12,\"bellType\":0,\"tech_number\":3208},{\"protype_id\":11,\"bellType\":0,\"tech_number\":8061},{\"protype_id\":11,\"bellType\":0,\"tech_number\":3216},{\"protype_id\":11,\"bellType\":0,\"tech_number\":6144},{\"protype_id\":11,\"bellType\":0,\"tech_number\":6132},{\"protype_id\":11,\"bellType\":0,\"tech_number\":6272}]";

JavaScriptSerializer js = new JavaScriptSerializer();
List<techItem> team = js.Deserialize<List<techItem>>(json);

 

//JsonConvert静态方式解析数据
var result = JsonConvert.DeserializeObject<T>(json);
var list = JsonConvert.DeserializeObject<List<T>>(json);

posted @ 2014-12-02 16:47  伤心木乃伊  阅读(264)  评论(0编辑  收藏  举报