Last active
March 16, 2019 09:42
-
-
Save marta-krzyk-dev/cd15584b8a2691d2dbdede0bac4fed4c to your computer and use it in GitHub Desktop.
How to detect/ignore duplicated properties in JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---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