StackOverflow Q28155169

CSharp · Console

/Program.cs

using System;
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static void Main()
	{
		string json = @"{
                ""Issuer"" : ""LOCAL AUTHORITY"",
                ""OriginalIssuer"" : ""LOCAL AUTHORITY"",
                ""Type"" : ""http://my.org/ws/2015/01/identity/claims/mytype"",
                ""Value"" : ""myvalue"",
                ""ValueType"" : ""http://www.w3.org/2001/XMLSchema#string""
            }";
		
		Claim claim = JsonConvert.DeserializeObject<Claim>(json, new ClaimConverter());
		
		Console.WriteLine(claim.Type);
		Console.WriteLine(claim.Value);
	}
}

class ClaimConverter : JsonConverter
{
	public override bool CanConvert(Type objectType)
	{
		return (objectType == typeof(System.Security.Claims.Claim));
	}
	
	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		JObject jo = JObject.Load(reader);
		string type = (string)jo["Type"];
		string value = (string)jo["Value"];
		string valueType = (string)jo["ValueType"];
		string issuer = (string)jo["Issuer"];
		string originalIssuer = (string)jo["OriginalIssuer"];
		return new Claim(type, value, valueType, issuer, originalIssuer);
	}
	
	public override bool CanWrite
	{
		get { return false; }
	}
	
	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		throw new NotImplementedException();
	}
}
;