C# : JSON Parser : Recursion example

Status
Not open for further replies.

kilnborn

Ars Scholae Palatinae
700
Yo folks.

I had a conference call with a potential client 2 days ago, with a 3rd party that is in the running for handling my potential client's cloud-based database management. During the call, they mentioned using REST calls to access their data. I'd never even heard of that (I've used SOAP for that), so I did what I always do in such situations, and explain that'd I'm unfamiliar with that, and I'll research it (it never pays to fake it with a potential client).

A bit of research later, and an email from the 3rd party, and I was successful in using RestSharp to retrieve a JSON object from their test server.

JSON is also alien to me, so I grabbed JSON.NET and took a look at it and yeah, no. I write highly abstracted programs that need to basically define themselves at runtime, rather than designtime, so that wasn't going to work.

Off to writing a JSON parser.

After a few hours of trying to keep my mind OFF the problem (mostly gaming) I realized the solution: deep recursion.

I wrote a prototype class to do JSON parsing into a format that holds whatever possible data the JSON object has. There's no comments, there's no error checking. This is down and dirty coding just to test whether a solution is feasible, but it DOES demonstrate, I think, recursion to those who can follow my code (I write dense code).

The parser (note that the class defines a List<> of itself):

Code:
using System.Collections.Generic;
using System.Linq;

namespace RESTConsole
{
    class JSONparser
    {
        string Name { get; set; }
        List<ValuePair> _values = new List<ValuePair>();
        List<JSONparser> _blocks = new List<JSONparser>();

        public JSONparser(string name, string json)
        {
            this.Name = name;

            ValuePairStep step = ValuePairStep.Field;
            string field = "";
            string value = "";

            int record = 0;
            int loc = 0;
            do
            {
                char c = json[loc];
                switch (c)
                {
                    case '{':
                        {
                            step = ValuePairStep.Field;
                            int blockEnd = 0;
                            int offset = 0;
                            while (true)
                            {
                                int close = json.IndexOf('}', (loc + 1) + offset);
                                string block = json.Substring(loc, (close + 1) - (loc + 1) + 1);
                                if (block.Count(f => f == '{') != block.Count(f => f == '}'))
                                {
                                    offset += (close - loc);
                                }
                                else
                                {
                                    blockEnd = close;
                                    break;
                                }
                            }
                            record++;
                            string jsonblk = json.Substring(loc + 1, (blockEnd - loc) + 1);
                            _blocks.Add(new JSONparser((field == "") ? record.ToString() : field, jsonblk));
                            loc += (blockEnd - loc);
                        }
                        break;

                    case ':':
                        step = ValuePairStep.Value;
                        break;

                    case '"':
                        {
                            int close = json.IndexOf('"', loc + 1);
                            string data = json.Substring(loc + 1, (close - loc) - 1);
                            if (step == ValuePairStep.Field)
                                field = data;
                            else
                            {
                                value = data;
                                step = ValuePairStep.Field;
                                _values.Add(new ValuePair(field, value));
                                field = "";
                                value = "";
                            }
                            loc += (close - loc);
                        }
                        break;

                    case ',':
                        step = ValuePairStep.Field;
                        break;
                }
                loc++;
            } while (loc < json.Length);
        }

        public string Output(int tabs)
        {
            string tab = "";
            for (int i = 1; i <= tabs; i++)
                tab += "\t";

            string output = "";

            foreach (JSONparser p in _blocks)
            {
                output += tab + p.Name + ":\n";
                output += p.Output(tabs + 1);
            }
            foreach (ValuePair vp in _values)
            {
                output += tab + vp.Name + " = " + vp.Value + "\n";
            }

            return output;
        }
    }

    class ValuePair
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public ValuePair(string name, string value)
        {
            this.Name = name;
            this.Value = value;
        }
    }

    enum ValuePairStep
    { Field, Value }
}

and my down and dirty test code:

Code:
using System;

namespace RESTConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "";

            using (System.IO.StreamReader sw = new System.IO.StreamReader("lotlist.txt"))
            {
                json = sw.ReadToEnd();
            }

            JSONparser jp = new JSONparser("lotlist", json);

            Console.Write(jp.Output(0));

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("parsedlist.txt"))
            {
                sw.Write(jp.Output(0));
            }


            Console.ReadLine();
        }
    }
}

Note: this is prototype code, just designed to demonstrate to myself that a thing is feasible.

If you can follow my code, you can see how deep recursion is useful.

Note: This code would need an overloaded Get() function, in order to retrieve data from the recursive object.

If you had the following JSON object:

Code:
[
    {
        "product":
        {
            "id":"eggs",
            "desc":"things laid by chickens",
            "price":"0.22"
        },
        "customer":
        {
            "id":"whlfds",
            "desc":"whole foods",
            <address shit who cares it's almost 4am>
        },
        "PurchaseOrder":"1234",
        "Price":"0.19"
    {
    <more food based orders, whatever>
]

The Get() function (which I haven't finalized) might work on jparser.Get("?PurchaseOrder=1234", "customer.id");

In this case, it'll return "whlfds".

Anyhow, I thought it was a good example of recursion, which can be extremely useful in some circumstances.
 
The " I write highly abstracted programs that need to basically define themselves at runtime, rather than designtime, so that wasn't going to work." kind of confuses the hell out of me.

I mean, I get that reflection can save bundles of work and sometimes there's nothing that makes quite as much sense as treating code as data, but this understanding of how programs should work seems to be very profoundly at odds with what anyone who works with other people would ever expect from idiomatic C#.
 

krimhorn

Ars Legatus Legionis
39,865
[url=http:/civis/viewtopic.php?p=31550783#p31550783:1colv0c4 said:
jxl[/url]":1colv0c4]I mean, I get that reflection can save bundles of work and sometimes there's nothing that makes quite as much sense as treating code as data, but this understanding of how programs should work seems to be very profoundly at odds with what anyone who works with other people would ever expect from idiomatic C#.
This. Clever for the sake of being clever is always bad.
 

hanser

Ars Legatus Legionis
43,847
Subscriptor++
[url=http:/civis/viewtopic.php?p=31555847#p31555847:o14z2wu3 said:
gnosis[/url]":eek:14z2wu3]
I write highly abstracted programs
But then you complected deserializing data with querying and traversing its contents. :confused:
Tbh, I could imagine someone in academia or finance doing something insane like this.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
This seems like a job for dynamic ExpandoObjects, tbh. Which play nicely with json.net.

This. If you really need dynamic behaviour let MSFT write it for you...

And if you want to avoid JSON.Net (because the strong naming choice is OMG I want to stab something) then either recompile it yourself without the strong name, or use something like this minimal single file drop in implementation
 
Status
Not open for further replies.