Created
May 16, 2014 12:25
-
-
Save kRapaille/6aef3cd83bcf30bea979 to your computer and use it in GitHub Desktop.
Dynamic property name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace ConsoleApplication3 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var test = JsonConvert.DeserializeObject<TestClass>("{ \"Test_en\" : 1}"); | |
} | |
} | |
[JsonConverter(typeof(MyConverter))] | |
class TestClass | |
{ | |
public int Test { get; set; } | |
} | |
class MyConverter : JsonConverter | |
{ | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
var jsonObject = JObject.Load(reader); | |
var readedProperties = jsonObject.Properties().ToList(); | |
const string language = "en"; | |
var test = new TestClass(); | |
var propertiesInfo = test.GetType().GetProperties(); | |
foreach (var propertyInfo in propertiesInfo) | |
{ | |
var type = propertyInfo.PropertyType; | |
var firstOrDefault = readedProperties | |
.FirstOrDefault(x => x.Name == string.Format("{0}_{1}", propertyInfo.Name, language)); | |
if (firstOrDefault != null) | |
{ | |
var value = Convert.ChangeType(firstOrDefault.Value, type); | |
propertyInfo.SetValue(test, value); | |
} | |
} | |
return test; | |
} | |
public override bool CanConvert(Type objectType) | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment