Skip to content

Instantly share code, notes, and snippets.

@Meligy
Created May 10, 2011 06:14
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 Meligy/963989 to your computer and use it in GitHub Desktop.
Save Meligy/963989 to your computer and use it in GitHub Desktop.
Seeing what capabilities JSON.NET has in working with slightly complex structures
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace SampleJson
{
class Program
{
static void Main(string[] args)
{
/*** ... Initializing ... ***/
// Creating some data to write and read back later.
var dataToWrite = new SortedDictionary<string, HashSet<int>>();
for (int number = 1; number <= 9; number++)
{
// This adds new entry, the key is a number saved as string
// The value is a list of numbers from 1 to given number.
// The list is inserted into a HashSet.
// The numbers are unique already but for testing
// So, example: for number = 3 we get
// Key = "3"
// Value = new HashSet() {1, 2, 3}
dataToWrite.Add(number.ToString(),
new HashSet<int>(Enumerable.Range(1, number)));
}
// Create the main class in JSON.NET to use in read / write
// Giving mandatory settings (that easy to create default one)
var jsonSerializer =
JsonSerializer.Create(new JsonSerializerSettings());
/*** ... Writing ... ***/
// Simulates Text Reader
// just like those used to write to file or response in ASP.NET
// But just writes to a string.
var outputWriter = new StringWriter();
// Create a serializer,
// give it some mandatory settings that we don't need to change
// Then write the dataToWrite to the text writer.
jsonSerializer.Serialize(outputWriter, dataToWrite);
// Get the string from the string writer JSON.NET wrote into
var jsonWritten = outputWriter.ToString();
/*** ... Output Written Value ... ***/
// Now we are done writing. Let's output what we wrote...
Console.WriteLine("JSON:");
Console.WriteLine(jsonWritten);
/*** ... Reading ... ***/
// We created a reader similar to our writer,
// but the library has diferent ways of readinf,
// We create a JSON reader from library, it's also easy!
var reader = new JsonTextReader(new StringReader(jsonWritten));
// Reading is easy. Define what type we expect,
// that's SortedDictionary<string, HashSet<int>>
// Amd pass the text to read.
var dataAfterRead = jsonSerializer
.Deserialize<SortedDictionary<string, HashSet<int>>>(reader);
/*** ... Output Read Value ... ***/
Console.WriteLine();
// Lets output the objects
Console.WriteLine("Objects:");
foreach (var entry in dataAfterRead)
{
// Example entry with key 3 will output -> "3: 1, 2, 3"
var entryText =
entry.Key + ": " + string.Join(", ", entry.Value);
Console.WriteLine(entryText);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment