Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View JsonContract.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace JsonTest
{
class Program
{
static void Main(string[] args)
{
var product = new Product{
id="1",
name="This is the name",
fields = new Dictionary<string,string> {
{"field1","test"},
{"field2","test2"}
}
};
 
var json = JsonConvert.SerializeObject(product);
 
Console.WriteLine(json);
 
var product2 = JsonConvert.DeserializeObject<Product>(json);
 
Console.ReadKey();
}
}
 
[JsonConverter(typeof(ProductConverter))]
public class Product
{
public Product()
{
fields = new Dictionary<string, string>();
}
 
public string id { get; set; }
public string name { get; set; }
public Dictionary<string, string> fields { get; set; }
}
 
public class ProductConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Product);
}
 
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var product = value as Product;
 
writer.WriteStartObject();
writer.WritePropertyName("id");
writer.WriteValue(product.id);
writer.WritePropertyName("name");
writer.WriteValue(product.name);
foreach (var item in product.fields)
{
writer.WritePropertyName(item.Key);
writer.WriteValue(item.Value);
}
writer.WriteEndObject();
}
 
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var product = existingValue as Product ?? new Product();
 
while (reader.Read())
{
if (reader.TokenType == JsonToken.EndObject) continue;
 
var value = reader.Value.ToString();
switch (value)
{
case "id":
product.id = reader.ReadAsString();
break;
case "name":
product.name = reader.ReadAsString();
break;
default:
product.fields.Add(value, reader.ReadAsString());
break;
}
 
}
 
return product;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.