Using JsonToStaticTypeConverter (part 1: introduction)

In this post i will write about the JsonToStaticTypeConverter project and how to use it. I created that project after implementing a Json parser. After finishing the parser i thought about where i could use this. So the result is an application that can generate c# classes out of a Json string. So with the  JsonToStaticTypeConverter you can generate c# classes and fill them with your Json data.

If we press generate a class Addresse im namespace MainTest in the file Addresse.cs in the folder C:\Projecte is generated out of the Json code (in this case { ‘street’ : ‘Teststreet’, ‘number’ : 1, ‘city’ : ‘Graz’ }. Here we see the generated c# file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JsonConverter;
namespace MainTest
{
public class Addresse : JsonStaticObject
{
public string street { get { return JsonSource.Find<string>("Addresse", "street"); } }
public double number { get { return JsonSource.Find<double>("Addresse", "number"); } }
public string city { get { return JsonSource.Find<string>("Addresse", "city"); } }
}
}

This c# file is inserted into the solution that wants to process the Json data. Here we see how the JsonConverter is used to generate the static structure of Addresse out of the Json data. We also need to reference the JsonConverter.dll from the JsonToStaticTypeConverter Project. Therefore we use the Deserialize method and overtake the Json string.

var jsonConverter = new JsonConverter<MainTest.Addresse>();
MainTest.Addresse address = jsonConverter.Deserialize(
    "{ 'street' : 'Gürtel', 'number' : 23, 'city' : 'Vienna' }");
var street = address.street;
var number = address.number;
var city = address.city;
Trace.WriteLine(street);
Trace.WriteLine(number);
Trace.WriteLine(city);

Here we see the trace result:

So with the JsonConverter it is possible to use the Json data due to a static structure. In the second post of this series i will write about the implementation of JsonToStaticTypeConverter and about the implementation of the Json ParserCombinator.

Advertisements