public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject obj = JObject.Load(reader); var api = new APIEndPoint(); api.name = (string)obj["name"]; api.url = (string)obj["url"]; api.requestParam = (string)obj["requestParam"]; if (obj["extraParams"] != null) { api.extraParams = new Dictionary <string, string>(); foreach (JProperty item in obj["extraParams"]) { api.extraParams.Add((string)item.Name, (string)item.Value); } } ; return(api); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { APIEndPoint api = (APIEndPoint)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(api.name); jsonWriter.WritePropertyName("url"); jsonWriter.WriteValue(api.url); jsonWriter.WritePropertyName("requestParam"); jsonWriter.WriteValue(api.requestParam); if (api.extraParams != null) { jsonWriter.WritePropertyName("extraParams"); jsonWriter.WriteStartObject(); foreach (KeyValuePair <string, string> item in api.extraParams) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(item.Key); jsonWriter.WriteValue(item.Value); jsonWriter.WriteEndObject(); } jsonWriter.WriteEndObject(); } jsonWriter.WriteEndObject(); // Write the closing of the root object // No need to close explicitly when inside a using statement } Console.WriteLine("Output: " + sb); }