/// <summary> /// Serializes the object to a json-object containing all properties of the object with their values. /// </summary> /// <param name="aiObject"></param> /// <returns></returns> public static string Serialize(object aiObject) { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) using (NullJsonWriter njw = new NullJsonWriter(sw)) { JsonSerializer ser = new JsonSerializer(); ser.Formatting = Formatting.Indented; ser.Serialize(njw, aiObject); } return(sb.ToString()); }
public static string Serialize(MainClass main) { // First, collect all instances of A var collector = new TypeInstanceCollector <A>(); var collectionSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, Converters = new JsonConverter[] { collector } }; using (var jsonWriter = new NullJsonWriter()) { JsonSerializer.CreateDefault(collectionSettings).Serialize(jsonWriter, main); } // Now serialize a proxt class with the collected instances of A at the beginning, to establish reference ids for all instances of B. var proxy = new RootProxy <MainClass, A> { Data = main, Table = collector.InstanceList }; var serializationSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }; return(JsonConvert.SerializeObject(proxy, Formatting.Indented, serializationSettings)); }
static void Main(string[] args) { // Set up a dummy object with some data. The object also has a bunch // of properties that are never set, so they have null values by default. Foo foo = new Foo { String = "test", Int = 123, Decimal = 3.14M, Object = new Bar { Name = "obj1" }, Array = new Bar[] { new Bar { Name = "obj2" } } }; // The serializer writes to the custom NullJsonWriter, which // writes to the StringWriter, which writes to the StringBuilder. // We could also use a StreamWriter in place of the StringWriter // if we wanted to write to a file or web response or some other stream. StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) using (NullJsonWriter njw = new NullJsonWriter(sw)) { JsonSerializer ser = new JsonSerializer(); ser.Formatting = Formatting.Indented; ser.Serialize(njw, foo); } // Get the JSON result from the StringBuilder and write it to the console. Console.WriteLine(sb.ToString()); }