| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using JetBrains.Annotations;
- using Newtonsoft.Json;
- using System;
- namespace Abp.Json
- {
- public static class JsonExtensions
- {
- /// <summary>
- /// Converts given object to JSON string.
- /// </summary>
- /// <returns></returns>
- public static string ToJsonString(this object obj, bool camelCase = false, bool indented = false)
- {
- var settings = new JsonSerializerSettings();
- if (camelCase)
- {
- settings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver();
- }
- else
- {
- settings.ContractResolver = new AbpContractResolver();
- }
- if (indented)
- {
- settings.Formatting = Formatting.Indented;
- }
-
- return ToJsonString(obj, settings);
- }
- /// <summary>
- /// Converts given object to JSON string using custom <see cref="JsonSerializerSettings"/>.
- /// </summary>
- /// <returns></returns>
- public static string ToJsonString(this object obj, JsonSerializerSettings settings)
- {
- return obj != null
- ? JsonConvert.SerializeObject(obj, settings)
- : default(string);
- }
- /// <summary>
- /// Returns deserialized string using default <see cref="JsonSerializerSettings"/>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="value"></param>
- /// <returns></returns>
- public static T FromJsonString<T>(this string value)
- {
- return value.FromJsonString<T>(new JsonSerializerSettings());
- }
- /// <summary>
- /// Returns deserialized string using custom <see cref="JsonSerializerSettings"/>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="value"></param>
- /// <param name="settings"></param>
- /// <returns></returns>
- public static T FromJsonString<T>(this string value, JsonSerializerSettings settings)
- {
- return value != null
- ? JsonConvert.DeserializeObject<T>(value, settings)
- : default(T);
- }
- /// <summary>
- /// Returns deserialized string using explicit <see cref="Type"/> and custom <see cref="JsonSerializerSettings"/>
- /// </summary>
- /// <param name="value"></param>
- /// <param name="type"></param>
- /// <param name="settings"></param>
- /// <returns></returns>
- public static object FromJsonString(this string value, [NotNull] Type type, JsonSerializerSettings settings)
- {
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
- return value != null
- ? JsonConvert.DeserializeObject(value, type, settings)
- : null;
- }
- }
- }
|