Am looking to Serialize a list using NewtonSoft JSON and i need to ignore one of the property while Serializing and i got the below code
public class Car
{
// included in JSON
public string Model { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
But am using this Specific class Car in many places in my application and i want to Exclude the option only in one place.
Can i dynamically add [JsonIgnore] in the Specific Place where i need ? How do i do that ?
No need to do the complicated stuff explained in the other answer.
NewtonSoft JSON has a built-in feature for that:
public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE()
{
if(someCondition){
return true;
}else{
return false;
}
}
It is called "conditional property serialization" and the documentation can be found here.
Warning: first of all, it is important to get rid of [JsonIgnore] above your {get;set;} property. Otherwise it will overwrite the ShouldSerializeXYZ behavior.
I think it would be best to use a custom IContractResolver to achieve this:
public class DynamicContractResolver : DefaultContractResolver
{
private readonly string _propertyNameToExclude;
public DynamicContractResolver(string propertyNameToExclude)
{
_propertyNameToExclude = propertyNameToExclude;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that are not named after the specified property.
properties =
properties.Where(p => string.Compare(p.PropertyName, _propertyNameToExclude, true) != 0).ToList();
return properties;
}
}
The LINQ may not be correct, I haven't had a chance to test this. You can then use it as follows:
string json = JsonConvert.SerializeObject(car, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("LastModified") });
Refer to the documentation for more information.
Based on #Underscore post above, I created a list of properties to exclude on serialization.
public class DynamicContractResolver : DefaultContractResolver {
private readonly string[] props;
public DynamicContractResolver(params string[] prop) {
this.props = prop;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
IList<JsonProperty> retval = base.CreateProperties(type, memberSerialization);
// return all the properties which are not in the ignore list
retval = retval.Where(p => !this.props.Contains(p.PropertyName)).ToList();
return retval;
}
}
Use:
string json = JsonConvert.SerializeObject(car, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("ID", "CreatedAt", "LastModified") });
With the reference Dynamically rename or ignore properties without changing the serialized class we can achieve JsonIgnore at run time. It's a workable solution.
Consider Person Class for example:
public class Person
{
// ignore property
[JsonIgnore]
public string Title { get; set; }
// rename property
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
Step 1: Create Class "PropertyRenameAndIgnoreSerializerContractResolver"
public class PropertyRenameAndIgnoreSerializerContractResolver : DefaultContractResolver
{
private readonly Dictionary<Type, HashSet<string>> _ignores;
private readonly Dictionary<Type, Dictionary<string, string>> _renames;
public PropertyRenameAndIgnoreSerializerContractResolver()
{
_ignores = new Dictionary<Type, HashSet<string>>();
_renames = new Dictionary<Type, Dictionary<string, string>>();
}
public void IgnoreProperty(Type type, params string[] jsonPropertyNames)
{
if (!_ignores.ContainsKey(type))
_ignores[type] = new HashSet<string>();
foreach (var prop in jsonPropertyNames)
_ignores[type].Add(prop);
}
public void RenameProperty(Type type, string propertyName, string newJsonPropertyName)
{
if (!_renames.ContainsKey(type))
_renames[type] = new Dictionary<string, string>();
_renames[type][propertyName] = newJsonPropertyName;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.DeclaringType, property.PropertyName))
{
property.ShouldSerialize = i => false;
property.Ignored = true;
}
if (IsRenamed(property.DeclaringType, property.PropertyName, out var newJsonPropertyName))
property.PropertyName = newJsonPropertyName;
return property;
}
private bool IsIgnored(Type type, string jsonPropertyName)
{
if (!_ignores.ContainsKey(type))
return false;
return _ignores[type].Contains(jsonPropertyName);
}
private bool IsRenamed(Type type, string jsonPropertyName, out string newJsonPropertyName)
{
Dictionary<string, string> renames;
if (!_renames.TryGetValue(type, out renames) || !renames.TryGetValue(jsonPropertyName, out newJsonPropertyName))
{
newJsonPropertyName = null;
return false;
}
return true;
}
}
Step 2: Add code in your method where Jsonignore want to apply
var person = new Person();
var jsonResolver = new PropertyRenameAndIgnoreSerializerContractResolver();
jsonResolver.IgnoreProperty(typeof(Person), "Title");
jsonResolver.RenameProperty(typeof(Person), "FirstName", "firstName");
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = jsonResolver;
var json = JsonConvert.SerializeObject(person, serializerSettings);
With respect to all correct answers I would like to add something. When you have nested properties with the same name so ignoring will effect on all properties with the same name. If you like to ignore a specific property you can do something like this:
public class DynamicContractResolver : DefaultContractResolver
{
private readonly string[] props;
public DynamicContractResolver(params string[] prop)
{
this.props = prop;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> retval = base.CreateProperties(type, memberSerialization);
return retval.Where(p => !this.props.Contains(p.DeclaringType.FullName + "." + p.PropertyName)).ToList();
}
}
then when you want to use it you can say:
var values = await _dbContext
.Set<EntityName>()
.Where(...).ToList();
var json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new DynamicContractResolver("Entities.Contact.Address1","Entities.User.Name","Entities.Event.Name")
});
The Address1 will be ignored in Contact not anywhere else.
Try this:
public static void IgnoreProperty<T, TR>(this T parameter, Expression<Func<T, TR>> propertyLambda)
{
var parameterType = parameter.GetType();
var propertyName = propertyLambda.GetReturnedPropertyName();
if (propertyName == null)
{
return;
}
var jsonPropertyAttribute = parameterType.GetProperty(propertyName).GetCustomAttribute<JsonPropertyAttribute>();
jsonPropertyAttribute.DefaultValueHandling = DefaultValueHandling.Ignore;
}
public static string GetReturnedPropertyName<T, TR>(this Expression<Func<T, TR>> propertyLambda)
{
var member = propertyLambda.Body as MemberExpression;
var memberPropertyInfo = member?.Member as PropertyInfo;
return memberPropertyInfo?.Name;
}
So you can do this:
carObject.IgnoreProperty(so => so.LastModified);
Based on the accepted answer it would be like:
[JsonIgnore]
public bool JsonIgnore { get; set; }
public bool ImageModified { get; set; }
public bool ShouldSerializeImageModified() => !JsonIgnore;
Whenever JsonIgnore is set to true it means that ImageModified won't be serialized, and JsonIgnore is ignored because of [JsonIgnore].
If there is a need to write code this way, it might be an indication of poor design. Probably there needs to be a DTO or ViewModel in the system, unless you want to dynamically disable/enable serialization of some properties.
Related
I have a custom attribute [Foo]
implemented as follows:
public class FooAttribute
: Attribute
{
}
Now I want to use the System.Text.Json.JsonSerializer to step into each field that has that attribute, in order to manipulate how is serialized and deserialized.
For example, if I have the following class
class SampleInt
{
[Foo]
public int Number { get; init; }
public int StandardNumber { get; init; }
public string Text { get; init; }
}
when I serialize an instance of this class, I want a custom int JsonConverter to apply only for that field.
public class IntJsonConverter
: JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// do whatever before reading if the text starts with "potato". But this should be triggered only if destination type has the Foo attribute. How?
return reader.GetInt32();
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
writer.WriteStringValue("potato" + value.ToString());
}
}
so that the serialization for
var sample =
new SampleInt
{
Number = 123,
StandardNumber = 456
Text = "bar"
};
like this
var serializeOptions = new JsonSerializerOptions();
var serializeOptions.Converters.Add(new IntJsonConverter());
var resultJson = JsonSerializer.Serialize(sample, serializeOptions);
results on the following json
{
"number": "potato123",
"standardNumber": 456,
"text": "bar"
}
and not in
{
"number": "potato123",
"standardNumber": "potato456",
"text": "bar"
}
In a similar manner, I want the deserialization to be conditional, and only use the custom converter if the destination field has the [Foo] attribute.
With Newtonsoft, this is possible using Contract Resolvers and overriding CreateProperties method like this.
public class SerializationContractResolver
: DefaultContractResolver
{
private readonly ICryptoTransform _encryptor;
private readonly FieldEncryptionDecryption _fieldEncryptionDecryption;
public SerializationContractResolver(
ICryptoTransform encryptor,
FieldEncryptionDecryption fieldEncryptionDecryption)
{
_encryptor = encryptor;
_fieldEncryptionDecryption = fieldEncryptionDecryption;
NamingStrategy = new CamelCaseNamingStrategy();
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var jsonProperty in properties)
{
var hasAttribute = HasAttribute(type, jsonProperty);
if (hasAttribute)
{
var serializationJsonConverter = new MyJsonConverter();
jsonProperty.Converter = serializationJsonConverter;
}
}
return properties;
}
private bool HasAttribute(Type type, JsonProperty jsonProperty)
{
var propertyInfo = type.GetProperty(jsonProperty.UnderlyingName);
if (propertyInfo is null)
{
return false;
}
var hasAttribute =
propertyInfo.CustomAttributes
.Any(x => x.AttributeType == typeof(FooAttribute));
var propertyType = propertyInfo.PropertyType;
var isSimpleValue = propertyType.IsValueType || propertyType == typeof(string);
var isSupportedField = isSimpleValue && hasPersonalDataAttribute;
return isSupportedField;
}
}
But I don't want to use Newtonsoft. I want to use the new dotnet System.Text.Json serializer. Is it possible to use it in a similar granular way?
How can I filter out the array objects which are having 0 elements from the ASP.NET Web API Model.
Ex: I'm am using the below method to filter null objects.
using Newtonsoft.Json;
public string FaxWork { get; set; }
[JsonProperty(PropertyName = "phoneWork", NullValueHandling = NullValueHandling.Ignore)]
How can I use something like above in order to filter out [] empty array objects?
Ex:
"postalAddress": [],
"electronicAddress": []
You can accomplish this using the conditional property serialization functionality of Json.NET.
If you just want to ignore a single member when its array value is empty, add a ShouldSerialize{PropertyName}() method to your class that returns false when you don't want it serialized, e.g.:
public class RootObject
{
public string[] PostalAddress { get; set; }
public bool ShouldSerializePostalAddress() { return PostalAddress != null && PostalAddress.Length > 0; }
}
If you need to do this for many different collection-valued members of many different types, you can create a custom contract resolver that automatically generates a ShouldSerialize predicate for all of then:
public class SkipEmptyCollectionsContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization)
.AddShouldSerializeEmptyCollections(this);
return property;
}
}
public static class JsonPropertyExtensions
{
public static JsonProperty AddShouldSerializeEmptyCollections(this JsonProperty property, IContractResolver resolver)
{
if (property == null)
throw new ArgumentNullException();
if ((typeof(IEnumerable).IsAssignableFrom(property.PropertyType) || property.PropertyType.IsAssignableFrom(typeof(IEnumerable)))
&& property.PropertyType != typeof(string)
&& property.Readable)
{
Predicate<object> shouldSerialize = (parent) =>
{
var value = property.ValueProvider.GetValue(parent);
if (value == null || value is string)
return true; // null properties are filtered by the NullValueHandling setting.
var contract = resolver.ResolveContract(value.GetType());
if (contract is JsonArrayContract)
{
return (value as IEnumerable).Any();
}
return true;
};
var oldShouldSerialize = property.ShouldSerialize;
if (oldShouldSerialize == null)
property.ShouldSerialize = shouldSerialize;
else
property.ShouldSerialize = (o) => shouldSerialize(o) && oldShouldSerialize(o);
}
return property;
}
}
public static class EnumerableExtensions
{
public static bool Any(this IEnumerable enumerable)
{
if (enumerable == null)
return false;
if (enumerable is ICollection)
{
return ((ICollection)enumerable).Count > 0;
}
var enumerator = enumerable.GetEnumerator();
using (enumerator as IDisposable)
{
return enumerator.MoveNext();
}
}
}
Then serialize using JsonSerializerSettings such as the following, which also enables camel casing of names:
var settings = new JsonSerializerSettings
{
ContractResolver = new SkipEmptyCollectionsContractResolver { NamingStrategy = new CamelCaseNamingStrategy() },
NullValueHandling = NullValueHandling.Ignore,
};
If you want to conditionally filter out empty collections using attributes, you could do so with the following contract resolver and attribute:
public enum EmptyArrayHandling
{
Include = 0,
Ignore = 1,
}
[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class JsonPropertyExtensionsAttribute : System.Attribute
{
public EmptyArrayHandling EmptyArrayHandling { get; set; }
}
public class ConditionallySkipEmptyCollectionsContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var attr = property.AttributeProvider.GetAttributes(typeof(JsonPropertyExtensionsAttribute), false).Cast<JsonPropertyExtensionsAttribute>().FirstOrDefault();
if (attr != null && attr.EmptyArrayHandling == EmptyArrayHandling.Ignore)
property = property.AddShouldSerializeEmptyCollections(this);
return property;
}
}
Then apply to your members as follows:
public class RootObject
{
[JsonPropertyExtensions(EmptyArrayHandling = EmptyArrayHandling.Ignore)]
public string[] PostalAddress { get; set; }
}
Note that if your "collection" is actually a complex LINQ query, the ShouldSerialize method will have to enumerate the first element of the query to see if it is empty, which may lead to poor performance because the query will get evaluated twice. To avoid this, you can evaluate the entire query as a list before serializing.
You may want to cache the contract resolver for best performance.
My goal is to serialize properties that don't have any attributes and properties which have a specific custom attribute.
For the following class:
public class Msg
{
public long Id { get; set; }
[CustomAttributeA]
public string Text { get; set; }
[CustomAttributeB]
public string Status { get; set; }
}
When I call a method Serialize(object, CustomAttributeA), I want to have the following output:
{
"Id" : someId,
"Text" : "some text"
}
And when I call Serialize(object, CustomAttributeB), I want to have following:
{
"Id" : someId,
"Status" : "some status"
}
I have read that it's possible to achieve this by creating a custom ContractResolver, but in this case must I create two separate contract resolvers?
You do not need two separate resolvers to achieve your goal. Just make the custom ContractResolver generic, where the type parameter represents the attribute you are looking for when serializing.
For example:
public class CustomResolver<T> : DefaultContractResolver where T : Attribute
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in list)
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null)
{
// if the property has any attribute other than
// the specific one we are seeking, don't serialize it
if (pi.GetCustomAttributes().Any() &&
pi.GetCustomAttribute<T>() == null)
{
prop.ShouldSerialize = obj => false;
}
}
}
return list;
}
}
Then, you can make a helper method to create the resolver and serialize your object:
public static string Serialize<T>(object obj) where T : Attribute
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver<T>(),
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(obj, settings);
}
When you want to serialize, call the helper like this:
string json = Serialize<CustomAttributeA>(msg);
Demo fiddle: https://dotnetfiddle.net/bRHbLy
We are using Json.Net in our project to serialize and deserialize json objects.
Our entities have some DateTime properties and I would like to be able to convert them into PersianCalender DateTime and to provide them as string in my json object:
for example we have this entity :
public class PersonCertificate
{
public DateTime CertificateDate{get;set;}
}
I would like to have a json object like this :
{
"PersianCertificateDate":"1395/10/10"
}
So I thought that would be great to have an attribute named "AsPersianDate" for example so that I could do something like this:
public class PersonCertificate
{
[JsonIgnore]
[AsPersianDate]
public DateTime CertificateDate{get;set;}
}
I know that I can have a custom contract resolver to intercept json property creation process but I don't know how should I tell Json.Net to deserialize PersianCertificateDate into CertificateDate ?
OK it was far more easier than I thought.Actually ContractResolver is responsible for getting and setting all property values so here's what I have done:
public class EntityContractResolver:DefaultContractResolver
{
private class PersianDateValueProvider:IValueProvider
{
private readonly PropertyInfo _propertyInfo;
public PersianDateValueProvider(PropertyInfo propertyInfo)
{
_propertyInfo = propertyInfo;
}
public void SetValue(object target, object value)
{
try
{
var date = value as string;
if(value==null && _propertyInfo.PropertyType==typeof(DateTime))
throw new InvalidDataException();
_propertyInfo.SetValue(target,date.ToGregorianDate());
}
catch (InvalidDataException)
{
throw new ValidationException(new[]
{
new ValidationError
{
ErrorMessage = "Date is not valid",
FieldName = _propertyInfo.Name,
TypeName = _propertyInfo.DeclaringType.FullName
}
});
}
}
public object GetValue(object target)
{
if(_propertyInfo.PropertyType.IsNullable() && _propertyInfo.GetValue(target)==null) return null;
try
{
return ((DateTime) _propertyInfo.GetValue(target)).ToPersian();
}
catch
{
return string.Empty;
}
}
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var list= base.CreateProperties(type, memberSerialization).ToList();
list.AddRange(type.GetProperties()
.Where(pInfo => IsAttributeDefined(pInfo,typeof(AsPersianDateAttribute))&& (pInfo.PropertyType == typeof (DateTime) || pInfo.PropertyType == typeof (DateTime?)))
.Select(CreatePersianDateTimeProperty));
return list;
}
private JsonProperty CreatePersianDateTimeProperty(PropertyInfo propertyInfo)
{
return new JsonProperty
{
PropertyName = "Persian"+propertyInfo.Name ,
PropertyType = typeof (string),
ValueProvider = new PersianDateValueProvider(propertyInfo),
Readable = true,
Writable = true
};
}
private bool IsAttributeDefined(PropertyInfo propertyInfo,Type attribute)
{
var metaDataAttribute = propertyInfo.DeclaringType.GetCustomAttribute<MetadataTypeAttribute>(true);
var metaDataProperty = metaDataAttribute?.MetadataClassType?.GetProperty(propertyInfo.Name);
var metaDataHasAttribute = metaDataProperty != null && Attribute.IsDefined(metaDataProperty, attribute);
return metaDataHasAttribute || Attribute.IsDefined(propertyInfo, attribute);
}
}
I have a bunch of classes that will be serialized to JSON at some point and for the sake of following both C# conventions on the back-end and JavaScript conventions on the front-end, I've been defining properties like this:
[JsonProperty(PropertyName="myFoo")]
public int MyFoo { get; set; }
So that in C# I can:
MyFoo = 10;
And in Javascript I can:
if (myFoo === 10)
But doing this for every property is tedious. Is there a quick and easy way to set the default way JSON.Net handles property names so it will automatically camel case unless told otherwise?
You can use the provided class Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver:
var serializer = new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jobj = JObject.FromObject(request, serializer);
In other words, you don't have to create a custom resolver yourself.
When serializing your object, pass in some custom settings.
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(yourObject, settings);
Better to use the new CamelCaseNamingStrategy (since 9.0.1):
new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
};
It does not override custom names set by JsonPropert('Name') by default. (You can change the behaviour by CamelCaseNamingStrategy(bool, bool) ctor.) So, does not need to create custom class like #Matt Burland's answer.
JObject.FromObject uses default settings from JsonConvert defaults.
There is a func property that you can assign like this:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
and whenever you call Jobject.FromObject, it will use this func to construct settings.
Since the accepted answer is link-only, I'm adding the actual code I ended up using (in case the link dies). It's largely the same as what was in the link:
// Automatic camel casing because I'm bored of putting [JsonProperty] on everything
// See: http://harald-muehlhoff.de/post/2013/05/10/Automatic-camelCase-naming-with-JsonNET-and-Microsoft-Web-API.aspx#.Uv43fvldWCl
public class CamelCase : CamelCasePropertyNamesContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member,
MemberSerialization memberSerialization)
{
var res = base.CreateProperty(member, memberSerialization);
var attrs = member.GetCustomAttributes(typeof(JsonPropertyAttribute), true);
if (attrs.Any())
{
var attr = (attrs[0] as JsonPropertyAttribute);
if (res.PropertyName != null && attr.PropertyName != null)
res.PropertyName = attr.PropertyName;
}
return res;
}
}
The only change I made was the addition of attr.PropertyName != null to the if clause because of the case where I had added something like:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string SomeProperty { get; set; }
And didn't want to specify the PropertyName (so it's null). The above will be serialized in JSON as someProperty.
You can use a custom contract resolver:
class MyContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var property in properties)
{
property.PropertyName = char.ToLower(property.PropertyName[0]) + string.Join("", property.PropertyName.Skip(1));
}
return properties;
}
}
And use it like:
class MyClass
{
public int MyProperty { get; set; }
public int MyProperty2 { get; set; }
}
var json = JsonConvert.SerializeObject(new MyClass(),
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new MyContractResolver() });
In .NET 5.0 you can use System.Text.Json and specifiy the ProperyNamingPolicy inside the JsonSerializerOptions
System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy
Here's a link to the Microsoft docs page on setting the property to use camel case.
var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
Class
public class WeatherForecastWithPropertyNameAttribute
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
[JsonPropertyName("Wind")]
public int WindSpeed { get; set; }
}
JSON output
{
"date": "2019-08-01T00:00:00-07:00",
"temperatureCelsius": 25,
"summary": "Hot",
"Wind": 35
}
public static JsonSerializer FormattingData()
{
var jsonSerializersettings = new JsonSerializer {
ContractResolver = new CamelCasePropertyNamesContractResolver() };
return jsonSerializersettings;
}
public static JObject CamelCaseData(JObject jObject)
{
var expandoConverter = new ExpandoObjectConverter();
dynamic camelCaseData =
JsonConvert.DeserializeObject(jObject.ToString(),
expandoConverter);
return JObject.FromObject(camelCaseData, FormattingData());
}