/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Runtime.Serialization.Json; using System.IO; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace WP7CordovaClassLib.Cordova.JSON { /// /// Provides JSON serialization/deserialization functionality. /// public static class JsonHelper { /// /// Serializes object to JSON string representation /// /// object to serialize /// JSON representation of the object. Returns 'null' string for null passed as argument public static string Serialize(object obj) { if (obj == null) { return "null"; } DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, obj); ms.Position = 0; string json = String.Empty; using (StreamReader sr = new StreamReader(ms)) { json = sr.ReadToEnd(); } ms.Close(); return json; } /// /// Parses json string to object instance /// /// type of the object /// json string representation of the object /// Deserialized object instance public static T Deserialize(string json) { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T)); object result = null; try { using (MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(json))) { result = deserializer.ReadObject(mem); } } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine("Failed to deserialize " + typeof(T) + " with JSON value :: " + json); } return (T)result; } } }