Skip to content

Instantly share code, notes, and snippets.

@LodewijkSioen
Created March 6, 2013 18:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LodewijkSioen/5101814 to your computer and use it in GitHub Desktop.
Save LodewijkSioen/5101814 to your computer and use it in GitHub Desktop.
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