Created
April 15, 2017 22:42
-
-
Save omerfarukz/f93184a07e7a1176b362e97d5d460240 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 System.Collections.Generic; | |
using System.IO; | |
using System.Text; | |
using System.Linq; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace jnbug | |
{ | |
class MainClass | |
{ | |
private static Encoding encoding = Encoding.UTF8; | |
public static void Main(string[] args) | |
{ | |
string path = DateTime.Now.ToString("ddHHmmss") + ".txt"; | |
var foo = new Foo(); | |
foo.Bar = new List<char>(new char[] {(char)56256 }); | |
var d = foo.AsDictionary(); | |
using (StreamWriter streamWriter = new StreamWriter(path, false, encoding)) | |
{ | |
using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter)) | |
{ | |
JsonSerializer serializer = new JsonSerializer(); | |
serializer.Converters.Add(new CharConverter()); | |
serializer.Serialize(jsonWriter, foo); | |
jsonWriter.Flush(); | |
} | |
} | |
using (StreamReader streamReader = new StreamReader(path, encoding, true)) | |
{ | |
using (JsonTextReader jsonReader = new JsonTextReader(streamReader)) | |
{ | |
JsonSerializer serializer = new JsonSerializer(); | |
serializer.Converters.Add(new CharConverter()); | |
var k = serializer.Deserialize<Foo>(jsonReader); | |
foreach (var item in k.Bar) | |
{ | |
Console.WriteLine((UInt16)item + " : " + item); | |
} | |
var d2 = k.AsDictionary(); | |
foreach (var item in d2) | |
{ | |
Console.WriteLine(item.Key + " : " + item.Value); | |
} | |
} | |
} | |
// Output: 56256 = 65533 | |
} | |
} | |
public class Foo | |
{ | |
//[JsonConverter(typeof(CharListConverter))] | |
public List<char> Bar { get; set;} | |
public IDictionary<char, UInt16> AsDictionary() | |
{ | |
return Bar.ToDictionary(f => f, (f) => (UInt16)f); | |
} | |
} | |
public class CharConverter : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
return objectType.Equals(typeof(char)); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
var token = JToken.Load(reader); | |
return (char)token.Value<UInt16>(); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
char character = (char)value; | |
writer.WriteValue(((UInt16)character)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment