using System; using System.IO; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Reflection;
namespace ConsoleApp1 { [DataContract] class MyConfig { [DataMember] public string IP { get; set; } [DataMember] public int Port { get; set; } }
class Program { const string CONFIG_JSON = ".config";
Type t = config.GetType(); PropertyInfo[] pArray = t.GetProperties(); for (int i = 0; i < pArray.Length; i++) { Console.WriteLine("属性" + i + ": " + pArray[i].Name + " " + pArray[i].GetValue(config)); }
Console.Read();
} }
public static class JSONSerializer<TType> where TType : class { /// <summary> /// Serializes an object to JSON /// </summary> public static string Serialize(TType instance) { var serializer = new DataContractJsonSerializer(typeof(TType)); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, instance); return Encoding.Default.GetString(stream.ToArray()); } }
/// <summary> /// DeSerializes an object from JSON /// </summary> public static TType DeSerialize(string json) { using (var stream = new MemoryStream(Encoding.Default.GetBytes(json))) { var serializer = new DataContractJsonSerializer(typeof(TType)); return serializer.ReadObject(stream) as TType; } } } }