Question

I have one JSON that is coming in a string format. I need to store it in a key-pair value or something like that. I am using asp.net 2.0 and can not use 3rd party DLL like Newtonsoft.Json.dll. I guess last option will be to use regular expression.

Can anybody please help me in this?

Was it helpful?

Solution

If you go to http://www.json.org/ and look towards the bottom of the page there are dozens of json libraries most of them open source, I believe they list 8 for C#. If you can not reference one of these libraries, I think your best bet would be to find one with a permissive license and simply add the code to your project.

Another idea is to look at the diagrams, grammer, and syntax at http://www.json.org/ and just write your own parser, but regex is NOT the way to do it. If you dont know how to write a parser you could look at one of the open source json libraries or start with something less complicated like a good CSV parser, here is a paper that looks pretty good: http://www.boyet.com/Articles/CsvParser.html

OTHER TIPS

It is possible to serialize JSON using JScript in C# into key/value pairs. You need to add a few references to your project. They're part of the .NET framework, you just need to add the references to your project. You'll need:

  • Microsoft.JSript
  • Microsoft.Vsa

First, the usings at the top of your class:

using Microsoft.JScript;
using Microsoft.JScript.Vsa;

Then the Engine that will execute the script needs to be initialized somewhere in your 'Page' code-behind:

VsaEngine Engine = VsaEngine.CreateEngine();

Then you just create this method and call it by passing in your JSON object:

object EvalJScript(string JScript)
{
    object result = null;
    try
    {
        result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }

    return result;
}

The type of object returned (if JSON is passed in) is a 'JSObject'. You can access its values as key/value pairs. Read the MSDN documentation for more details on this object.

Here's an example of using the code:

string json = "({Name:\"Dan\",Occupation:\"Developer\"})";

JSObject o = EvalJScript(json) as JSObject;

string name = o["Name"] as string; // Value of 'name' will be 'Dan'

Could you use JScript.NET?

If so, should be easy enough with eval() - then just loop through the objects returned and translate into KeyValuePair's or whatever

You will need to use jscript.net as the code behind language, but other pages of your site should be fine to stay as c# if thats what you prefer.

As mentioned in previous comment, you will need to be aware of the security aspects and risks - only use eval if you trust the JSON you're parsing!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top