public static string ToJson(object obj) { if (obj == null) { return(string.Empty); } Type t = obj.GetType(); if (!IsJsonSerializable(t)) { return(null); } StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{"); // use to stroage key-values and then concat them // List <string> keyValues = new List <string>(); foreach (var keyVal in GetPropertyInfoList(t)) { object val = keyVal.Value.GetValue(obj, null); string jsonValue = string.Empty; if (val == null) { jsonValue = "null"; keyValues.Add(string.Format("\"{0}\":{1}", keyVal.Key, jsonValue)); continue; } // If mark JSONRootAttribute, the we use its json value // otherwise, we use its property values // if (IsJsonSerializable(val.GetType())) { jsonValue = APJsonSerializer.ToJson(val); keyValues.Add(string.Format("\"{0}\":{1}", keyVal.Key, jsonValue)); } else if (val is IList) { jsonValue = ToJsonArray(val as IList); keyValues.Add(string.Format("\"{0}\":{1}", keyVal.Key, jsonValue)); } else { jsonValue = val.ToString(); keyValues.Add(string.Format("\"{0}\":\"{1}\"", keyVal.Key, jsonValue)); } } jsonBuilder.Append(string.Join(",", keyValues.ToArray())); jsonBuilder.Append("}"); return(jsonBuilder.ToString()); }
public static void UpdateJsonInAsset(APAsset asset) { string json = APJsonSerializer.ToJson(asset); asset.Json = SafeJson(json); }