using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
public
class
Item
{
[JsonProperty(
"email"
)]
public
string Email { get; set; }
[JsonProperty(
"timestamp"
)]
public
int Timestamp { get; set; }
[JsonProperty(
"event"
)]
public
string Event { get; set; }
[JsonProperty(
"category"
)]
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
public
List<string> Categories { get; set; }
}
public
class
SingleOrArrayConverter<T> : JsonConverter
{
public
override bool CanConvert(Type objectType)
{
return
objectType == typeof(List<T>);
}
public
override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if
(token.Type == JTokenType.Array)
{
return
token.ToObject<List<T>>();
}
if
(token.Type == JTokenType.Null)
{
return
null;
}
return
new
List<T> { token.ToObject<T>() };
}
public
override bool CanWrite => false;
public
override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw
new
NotImplementedException();
}
}
public
class
Example
{
public
static
void Main(string[] args)
{
string json = @"
[
{
""
email
""
:
""
test1@example.com
""
,
""
timestamp
""
: 1337966815,
""
category
""
: [
""
newuser
""
,
""
transactional
""
],
""
event
""
:
""
open
""
},
{
""
email
""
:
""
test2@example.com
""
,
""
timestamp
""
: 1337966815,
""
category
""
:
""
olduser
""
,
""
event
""
:
""
open
""
}
]";
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach
(
var
item in items)
{
Console.WriteLine($
"Email: {item.Email}, Timestamp: {item.Timestamp}, Event: {item.Event}, Categories: {string.Join("
,
", item.Categories)}"
);
}
}
}