Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active March 16, 2019 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marta-krzyk-dev/cd15584b8a2691d2dbdede0bac4fed4c to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/cd15584b8a2691d2dbdede0bac4fed4c to your computer and use it in GitHub Desktop.
How to detect/ignore duplicated properties in JSON
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DuplicatedJsonProperties
{
class DuplicatedJsonProperties
{
private const string data =
@"{
""language"": ""esperanto"",
""title"": ""Primeiro Manual de Esperanto"",
""title"": ""Fundamento de Esperanto"",
""author"" : ""Ludwik Lejzer Zamenhof""
}";
static void Main(string[] args)
{
Console.WriteLine("---Input---");
Console.WriteLine(data);
PrintJson("Throw exception on duplicates", DuplicatePropertyNameHandling.Error);
PrintJson("Ignore duplicates", DuplicatePropertyNameHandling.Ignore);
PrintJson("Replace duplicates with the last property", DuplicatePropertyNameHandling.Replace);
Console.ReadKey();
}
private static void PrintJson(string header, DuplicatePropertyNameHandling duplicateFlag)
{
try
{
Console.WriteLine();
Console.WriteLine("---" + header + "---");
JsonLoadSettings jsonLoadSettings = (duplicateFlag == DuplicatePropertyNameHandling.Replace)
? null
: new JsonLoadSettings { DuplicatePropertyNameHandling = duplicateFlag };
JToken jToken = JToken.Parse(data, jsonLoadSettings);
Console.WriteLine(jToken.ToString(Formatting.Indented));
Console.WriteLine();
}
catch (JsonReaderException jsonReaderException)
{
Console.WriteLine("Exception thrown: " + jsonReaderException.Message);
}
}
}
}
---Input---
{
"language": "esperanto",
"title": "Primeiro Manual de Esperanto",
"title": "Fundamento de Esperanto",
"author" : "Ludwik Lejzer Zamenhof"
}
---Throw exception on duplicates---
Exception thrown: Property with the name 'title' already exists in the current JSON object. Path 'title', line 4, position 9.
---Ignore duplicates---
{
"language": "esperanto",
"title": "Primeiro Manual de Esperanto",
"author": "Ludwik Lejzer Zamenhof"
}
---Replace duplicates with the last property---
{
"language": "esperanto",
"title": "Fundamento de Esperanto",
"author": "Ludwik Lejzer Zamenhof"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment