Custom json parser (Newtonsoft)

If you need custom json parser, this sample maybe helping for you,


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CustomJsonParser
{
class Program
{
static void Main(string[] args)
{
JsonConverter[] converters = { new MyConverter() };
string jsonData = "sampe json data";
Container container = JsonConvert.DeserializeObject<Container>(jsonData, new JsonSerializerSettings() { Converters = converters });
}
}

public class Container
{
public List<Room> RoomList { get; set; }
public List<Home> HomeSectionList { get; set; }
}

public interface Home
{ }

public class Door : Home {
public String DoorName { get; set; }
}

public class Windows : Home {
public String WindowName { get; set; }
}

public class Room {
public String RoomName { get; set; }
}

public class MyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Home));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);

if (FindClassName(jo["__class"].Value<string>(), "Room"))
return jo.ToObject<Windows>(serializer);

if (FindClassName(jo["__class"].Value<string>(), "Door"))
return jo.ToObject<Door>(serializer);

if (FindClassName(jo["__class"].Value<string>(), "Window"))
return jo.ToObject<Windows>(serializer);

return null;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public bool FindClassName(string jObjectString, string className)
{
bool existClassName = jObjectString.Split(':').First().Equals(className);

return existClassName;
}
}

}

Advertisements

#csharp-deserialize, #custom-deserialize, #interface-deserialize, #json, #json-deserialize, #newtonsoft