using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading.Tasks; namespace Monaco.Helpers { public interface IJsonable { string ToJson(); } public static class Json { /// /// Converts an array of strings to a JSON based string array. /// /// /// public static string StringArray([ReadOnlyArray] string[] strings) { StringBuilder output = new StringBuilder("[", 100); foreach (string msg in strings) { output.Append(String.Format("\"{0}\",", msg)); } if (strings.Length > 0) { output.Remove(output.Length - 1, 1); // Remove Trailing Comma } output.Append("]"); return output.ToString(); } /// /// Converts an array of Jsonable objects to JSON based array. /// /// /// public static string ObjectArray(IEnumerable objects) { StringBuilder output = new StringBuilder("[", 100); foreach (var obj in objects) { output.Append(String.Format("{0},", obj.ToJson())); } if (objects.Count() > 0) { output.Remove(output.Length - 1, 1); // Remove Trailing Comma } output.Append("]"); return output.ToString(); } /// /// Wrap a JSON string in a Parse statement for export. /// Escapes double-quotes. /// /// /// public static string Parse(string json) { return String.Format("JSON.parse(\"{0}\")", json.Replace("\"", "\\\"")); } } }