Skip to content

Instantly share code, notes, and snippets.

@FSou1
Last active April 14, 2017 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FSou1/daeff50471419de025f7dab9c744df1c to your computer and use it in GitHub Desktop.
Save FSou1/daeff50471419de025f7dab9c744df1c to your computer and use it in GitHub Desktop.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
const string response = @"
{
contacts: [
{
type: ""email"",
value: ""hello@world.com""
},
{
type: ""cell"",
value: {
code: ""+7"",
number: ""9779998877"",
countryId: 123
}
},
{
type: ""vk_id"",
value: 12342341
}]
}
";
var resume = JsonConvert.DeserializeObject<Resume>(response, new ContactConverter());
Console.WriteLine(JsonConvert.SerializeObject(resume,
new JsonSerializerSettings {
Formatting = Formatting.Indented
}
));
}
}
public class ContactConverter : CustomCreationConverter<IContact> {
public override IContact Create(Type objectType) {
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var jObject = JObject.Load(reader);
var target = CreateContact(jObject);
return target;
}
/// <summary>
/// Create concrete contact base on contactType value
/// </summary>
/// <param name="jObject"></param>
/// <returns></returns>
private IContact CreateContact(JObject jObject) {
var contactType = (string)jObject.Property("type");
var json = jObject.ToString();
switch (contactType) {
case "email": {
return DeserializeObject<EmailContact>(json);
}
case "cell": {
return DeserializeObject<PhoneContact>(json);
}
case "vk_id": {
return DeserializeObject<VkContact>(json);
}
default:
throw new NotSupportedException("Unexpected contactType: " + contactType);
}
}
private T DeserializeObject<T>(string json) => JsonConvert.DeserializeObject<T>(json);
}
public class Resume {
public IList<IContact> Contacts { get; set; }
}
public interface IContact {
string Type { get; set; }
}
public class EmailContact : IContact {
public string Type { get; set; }
public string Value { get; set; }
}
public class PhoneContact : IContact {
public string Type { get; set; }
public PhoneContactValue Value { get; set; }
}
public class VkContact : IContact {
public string Type { get; set; }
public int Value { get; set; }
}
public class PhoneContactValue {
public string Code { get; set; }
public string Number { get; set; }
public int CountryId { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment