public static string GetJsonString(this IJsonable data) {
using (MemoryStream memoryStrem = new MemoryStream()) {
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(data.GetType());
StringBuilder stringBuilder = new StringBuilder();
dataContractJsonSerializer.WriteObject(memoryStrem, data);
stringBuilder.Append(Encoding.UTF8.GetString(memoryStrem.ToArray()));
return stringBuilder.ToString();
}
}
JSON字符串 逆轉(zhuǎn)為 類
public static T GetJsonObject<T>(this string jsonString) {
using (MemoryStream memoryStrem = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) {
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
T jsonObject = (T) dataContractJsonSerializer.ReadObject(memoryStrem);
memoryStrem.Close();
return jsonObject;
}
}