CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// https://stackoverflow.com/questions/48791322/how-to-ignore-empty-arrays-using-jsonconvert-deserializeobject
public class IgnoreUnexpectedArraysConverter<T> : IgnoreUnexpectedArraysConverterBase
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
public class IgnoreUnexpectedArraysConverter : IgnoreUnexpectedArraysConverterBase
{
readonly IContractResolver resolver;
public IgnoreUnexpectedArraysConverter(IContractResolver resolver)
{
if (resolver == null)
throw new ArgumentNullException();
this.resolver = resolver;
}
public override bool CanConvert(Type objectType)
{
if (objectType.IsPrimitive || objectType == typeof(string))
return false;
return resolver.ResolveContract(objectType) is JsonObjectContract;
}
}
public abstract class IgnoreUnexpectedArraysConverterBase : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (!(contract is JsonObjectContract))
{
throw new JsonSerializationException(string.Format("{0} is not a JSON object", objectType));
}
do
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.Comment)
continue;
else if (reader.TokenType == JsonToken.StartArray)
{
var array = JArray.Load(reader);
if (array.Count > 0)
throw new JsonSerializationException(string.Format("Array was not empty."));
return existingValue ?? contract.DefaultCreator();
}
else if (reader.TokenType == JsonToken.StartObject)
{
// Prevent infinite recursion by using Populate()
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;
}
else
{
throw new JsonSerializationException(string.Format("Unexpected token {0}", reader.TokenType));
}
}
while (reader.Read());
throw new JsonSerializationException("Unexpected end of JSON.");
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class Item
{
public string category_name { get; set; }
public string category_id { get; set; }
public bool is_primary { get; set; }
}
public class Categories
{
public int count { get; set; }
public List<Item> items { get; set; }
}
public class Venue
{
public int venue_id { get; set; }
public string venue_name { get; set; }
public string venue_slug { get; set; }
public string primary_category { get; set; }
public string parent_category_id { get; set; }
public Categories categories { get; set; }
public bool is_verified { get; set; }
}
public class Rootobject
{
public Venue venue { get; set; }
}
class TestClass
{
public static void Test()
{
foreach (var json in GetJson())
{
Test<Rootobject>(json);
}
}
public static void Test<Rootobject>(string jsonString)
{
var resolver = new DefaultContractResolver(); // Cache for performance
var settings = new JsonSerializerSettings
{
ContractResolver = resolver,
Converters = { new IgnoreUnexpectedArraysConverter(resolver) },
};
var userInfo = JsonConvert.DeserializeObject<Rootobject>(jsonString, settings);
var json2 = JsonConvert.SerializeObject(userInfo, Formatting.Indented, settings);
Console.WriteLine(json2);
}
static IEnumerable<string> GetJson()
{
var json = new[]
{
@"
{
""venue"":{
""venue_id"":696895,
""venue_name"":""Blackfinn Ameripub"",
""venue_slug"":""blackfinn-ameripub"",
""primary_category"":""Food"",
""parent_category_id"":""4d4b7105d754a06374d81259"",
""categories"":{
""count"":1,
""items"":[
{
""category_name"":""American Restaurant"",
""category_id"":""4bf58dd8d48988d14e941735"",
""is_primary"":true
}
]
},
""is_verified"":false
}
}",
@"
{
""venue"":[]
}",
@"
{
""venue"":/* Some comments to mess you up */ []
}",
@"
{
""venue"":{
""venue_id"":696895,
""venue_name"":""Blackfinn Ameripub"",
""venue_slug"":""blackfinn-ameripub"",
""primary_category"":""Food"",
""parent_category_id"":""4d4b7105d754a06374d81259"",
""categories"": [],
""is_verified"":false
}
}
",
@"
{
""venue"":{
""venue_id"":696895,
""venue_name"":""Blackfinn Ameripub"",
""venue_slug"":""blackfinn-ameripub"",
""primary_category"":""Food"",
""parent_category_id"":""4d4b7105d754a06374d81259"",
""categories"":{
""count"":1,
""items"":[
/* Some comments to mess you up */ []
]
},
""is_verified"":false
}
}"
};
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
IsTrue(value, "failed");
}
public static void IsTrue(bool value, string message)
{
if (value == false)
throw new AssertionFailedException(message ?? "failed");
}
}