/// <summary> /// Convert a value to JSON. /// </summary> /// <param name="o">The value to convert. Supported types are: Boolean, String, Byte, (U)Int16, (U)Int32, Float, Double, Decimal, JsonObject, JsonArray, Array, Object and null.</param> /// <returns>The JSON object as a string or null when the value type is not supported.</returns> /// <remarks>For objects, only public fields are converted.</remarks> public string ToJson(object o) { if (o == null) { return("null"); } Type type = o.GetType(); switch (type.Name) { case "Boolean": return((bool)o ? "true" : "false"); case "String": return("\"" + JsEncode((string)o) + "\""); case "Byte": case "Int16": case "UInt16": case "Int32": case "UInt32": case "Single": case "Double": case "Decimal": case "JsonObject": case "JsonArray": return(o.ToString()); } if (type.IsArray) { JsonArray jsonArray = new JsonArray(); foreach (object i in (Array)o) { jsonArray.Add(i); } return(jsonArray.ToString()); } if (type.IsClass) { JsonObject jsonObject = new JsonObject(); FieldInfo[] fields = type.GetFields(); foreach (FieldInfo info in fields) { jsonObject.Add(info.Name, info.GetValue(o)); } return(jsonObject.ToString()); } return(null); }
/// <summary> /// Convert a value to JSON. /// </summary> /// <param name="o">The value to convert. Supported types are: Boolean, String, Byte, (U)Int16, (U)Int32, Float, Double, Decimal, JsonObject, JsonArray, Array, Object and null.</param> /// <returns>The JSON object as a string or null when the value type is not supported.</returns> /// <remarks>For objects, only public fields are converted.</remarks> public static string ToJson(object o) { if (o == null) return "null"; Type type = o.GetType(); switch (type.Name) { case "Boolean": return (bool)o ? "true" : "false"; case "String": return "\"" + JsEncode((string)o) + "\""; case "Byte": case "Int16": case "UInt16": case "Int32": case "UInt32": case "Single": case "Double": case "Decimal": case "JsonObject": case "JsonArray": return o.ToString(); } if (type.IsArray) { JsonArray jsonArray = new JsonArray(); foreach (object i in (Array)o) jsonArray.Add(i); return jsonArray.ToString(); } if (type.IsClass) { JsonObject jsonObject = new JsonObject(); FieldInfo[] fields = type.GetFields(); foreach (FieldInfo info in fields) jsonObject.Add(info.Name, info.GetValue(o)); return jsonObject.ToString(); } return null; }