Last active
January 21, 2019 10:52
-
-
Save emilkje/a953e874df676f4bf3ad793fe412a3dc to your computer and use it in GitHub Desktop.
This file contains 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 Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace jsonconvert | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
var str = "{\"user\":\"{\\\"username\\\":\\\"test\\\"}\"}"; | |
var res = JsonConvert.DeserializeObject<Payload>(str); | |
Console.ReadLine(); | |
} | |
} | |
class User { | |
[JsonProperty("username")] | |
public string Username { get; set; } | |
} | |
class Payload { | |
[JsonConverter(typeof(PropertyConverter<User>))] | |
[JsonProperty("user")] | |
public User User { get; set; } | |
} | |
class PropertyConverter<TProperty> : JsonConverter<TProperty> | |
{ | |
public override TProperty ReadJson(JsonReader reader, Type objectType, TProperty existingValue, bool hasExistingValue, JsonSerializer serializer) | |
{ | |
JToken token = JToken.Load(reader); | |
if(token.Type == JTokenType.String){ | |
var u = token.ToString(); | |
return JsonConvert.DeserializeObject<TProperty>(u); | |
} | |
return default(TProperty); | |
} | |
public override void WriteJson(JsonWriter writer, TProperty value, JsonSerializer serializer) | |
{ | |
serializer.Serialize(writer, value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment