public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject obj = JObject.Load(reader); var tc = new TokenExtractor(); tc.name = (string)obj["name"]; List <char> delimiters = new List <char>(); foreach (char o in obj["delimiters"]) { delimiters.Add((char)o); } tc.delimiters = delimiters.ToArray(); JArray arr = obj["positions"].ToObject <JArray>(); tc.indexMap = new Dictionary <int, ExpectedValue>(); for (int i = 0; i < arr.Count; i++) { tc.indexMap[i] = new ExpectedValue((int)arr[i][i.ToString()]["type"], (string)arr[i][i.ToString()]["expected"]); } return(tc); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { TokenExtractor tc = (TokenExtractor)value; var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) using (var jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); // Write the opening of the root object jsonWriter.WritePropertyName("name"); jsonWriter.WriteValue(tc.name); jsonWriter.WritePropertyName("delimiters"); jsonWriter.WriteStartArray(); foreach (char d in tc.delimiters) { jsonWriter.WriteValue(d); } jsonWriter.WriteEndArray(); jsonWriter.WritePropertyName("positions"); jsonWriter.WriteStartArray(); foreach (KeyValuePair <int, ExpectedValue> entry in tc.indexMap) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(entry.Key.ToString()); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("type"); jsonWriter.WriteValue(entry.Value.type.ToString()); jsonWriter.WritePropertyName("expected"); jsonWriter.WriteValue(entry.Value.value); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); // Write the closing of the root object // No need to close explicitly when inside a using statement } Console.WriteLine("Output: " + sb); }