JSON string to list or other usable format in asp.net 2.0 - asp.net

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?

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

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!

Related

How to convert byte[] to ObjectParameter in ASP.net

I have a byte[] and wanna convert it to object parameter in asp.net.
byte[] version =98471574580;
and I have One method that wants "ObjectParametere version".I must convert byte[] version to
ObjectParametere.
The way to do this has a few steps that if you follow in future shoudl save you needing to ask this sort of question again.
1) Look at the documentation for the class you want to use. It is found here: http://msdn.microsoft.com/en-us/library/system.data.objects.objectparameter(v=vs.110).aspx googleing for "ObjectParameter" returns it as top hit for me. Google might have noticed me doing a lot of MSDN searches though and bumping them to the top so if in doubt try adding MSDN or c# to the search.
2) Look for how to create an instance of the object. This would usually be through constructors. Sometimes you may use static methods but constructors are usual and in fact there are two here we can consider.
3) Decide which constructor to use. One takes a name and a type. One takes a name and a value. Since we have a value this seems like the one to choose.
4) Call the constructor you have decided to use and assign it to a variable (or use it directly in your code). In this case the syntax would be var objParam = new ObjectParameter("version", version);.
Some of these steps might be short circuited. For example if you are programming in Visual Studio then typing new ObjectParameter( should then offer intellisense help on what constructors are available, saving the need to look the documentation up online.

Is it possible to return a html table from a WebMethod?

Using a WebMethod, I get a value needed to create a HTML Table and populate it.
Once it's done, I need the Table to be displayed.
Is it possible ?
Can a web service return an HTML table? Yes. Should you do it that way? Probably not. Please consider 'separating the concerns' so that the service is responsible only for returning the data. Then the consumer of the data can format it as needed. One possible implementation would be for the service to return XML and the 'presenter' to transform it with XSLT into the desired Table. In the long run, the code will be easier to maintain and understand. (Trust me; I've seen a project that had 2,500+ lines of string concatenation that built an HTML string. NOT fun!) As an added bonus, the web service's response will be much smaller.
You can return a string from a WebMethod, which means you could return a string that represents html... then render that string (taking care of required encoding) I cant say much more that that not knowing any more...
Create the markup in a variable and do Response.Write.
StringBuilder strHtml=new StringBuilder();
strHtml.Append("<table>");
strHtml.Append("<tr><th>Name</th></tr>");
strHtml.Append("<tr><td>Jon</td></tr>");
strHtml.Append("<tr><td>Marc</td></tr>");
strHtml.Append("<tr><td>Jared</td></tr>");
strHtml.Append("</table>");
Response.Write(strHtml.ToString());

Why have a separate call to get Json?

I need to get some Json to the client side from the server and it's somewhat troublesome as almost all tutorials assume an Ajax call to a separate action to get the Json.
This led me to think that there must be some reason why it is done this way. In Asp.Net MVC we can pass a Model along with the view to get the information but we can't seem to easily pass a Json object. Instead you are supposed to make a separate call to get this information.
What if the Json info is known when the page is generated, why not generate it at the same time?
I'm sorry if I wasn't clear enough. While it's nice to hear of ways to get Json to the client, the question is actually whether there is a specific reason the Ajax call method is much more popular, like security or anything like that.
Can you put something like this into your view? (rough pseudo code, assuming using a Razor view)
< script >
var myJSON = { Field: #model.Field, Field2: #model.Field2 };
< /script >
Because you do not need both at the same time... on the first call will be to get html (the view of the data - represented by a view model), and any ajax calls will be to get the possibly updated data (json serialized view model).
No reason why you can't. You could use the javacript serializer to create a JSON string that drop on the page. You could also create an action that return the json string that you called from a script tag.
What you want if you're using KnockOut, would be the Mapping plugin that turns an ordinary JS object, like that generated above, into an observable ready for KnockOut to use. See here from info. http://knockoutjs.com/documentation/plugins-mapping.html
You can use content-negotiation by setting accept header. This is considered a best practice (and according to some RESTful).
This needs to be supported and implemented at server as well. ASP NET MVC does not make it easy to support content-negotiation and you have to implement it yourself by if-else or using ActionFilter and implementing action selector.

NHibernate.IFutureValue<> when serialized includes .Value

I'm building an ASP.NET (2.0, no, I can't change it) site with NHibernate, and have a custom JSON converter so I can not-serialize properties I want hidden from the client. This lets me just return the objects, and never have to worry about their serialized values - they're always secure.
Unfortunately, it appears that if I use query.FutureValue<class>(), the object that gets serialized is first the NHibernate.Impl.FutureValue<class> and not my entity, which means I get JSON that looks like this if I throw it in a dictionary and return it to the client:
{key: { Value: { /* my serialized object properties */ } }
Previously I discovered that I can't get any interfaces to work in ASP's JavaScriptConverter implementations... only regular or abstract classes. So returning typeof(IFutureValue<MyBaseClass>) as a supported type means my converter is completely ignored. I can catch MyBaseClass, because I refactored things earlier to use an abstract base instead of an interface, but not the interface.
And then I discover that the FutureValue implementation in .Impl is internal to the assembly, or some other such nonsense that only serves to make my .NET experience even more painful. So I can't use typeof(FutureValue<MyBaseClass>) to handle it all, because FutureValue exists only in my debugging sessions.
Is there a way to get the class type out of the assembly? Or a way to convince ASP that interfaces do in fact have uses? Or might there be some superclass I can access that would let me get around the whole issue?
Help! I like my Futures, it lets me batch a whole heck-ton of calls at once!
(if something isn't clear, or you want more code, by all means, ask! I can post quite a bit.)
If I'm understanding you correctly, it seems you are mixing things a together a little bit.
It sounds like you're trying to serialize an instance of query.FutureValue<class>(), which unsurprisingly gives you just that: a JSON object where the Value fields has JSON representing your entity.
To me it sounds like you really want to just serialize query.FutureValue<class>().Value.
Using NHibernate futures like this gives you little benefit though, so you're probably after something like:
var future1 = query1.FutureValue<SomeEntity>();
var future2 = query2.FutureValue<AnotherEntity>();
var json1 = serializer.Serialize(future1.Value); //<BAM! Multi-query gets fired!
var json2 = serializer.Serialize(future2.Value);
Does that make sense?

json Data Output in ASP.NET

I am using the ASP.NET command
var returnValue = new JsonResult { Data = items.Skip((pageNumber - 1) * pageSize).Take(pageSize) };
return returnValue;
to return the paged contents of a table via JSON, but when I got to try to parse it, in jQuery, the $.each takes each character as an individual element.
The output from that is along the lines of
[{"ItemNumber":1,"Description":"Description1"}, {"ItemNumber":2,"Description":"Description2"}]
listing all the rows and fields correctly. However this doesn't look like correctly formatted JSON to me (I beleive it should be encased in {}), is it?
If not what should I be doing to correctly output the table? If so, how can I loop round each element in jQuery, and extract the field values?
This is correctly formatted JSON.
You could try evaluating it with
var someVar = eval(jsonValue);
but this may lead to XSS.
Or even use this plugin.
This question may be related too.
Actually, using eval might be dangerous: unlike the case when it's enclosed in {}, it's possible to subvert the construction of an array. This occurs when eval tries to create an array using the Array constructor. See this post.
If you're not worried about that, you can use eval - for safety, the JQuery plugin in wtaniguchi's answer.
Can you not loop through like this?
for (i = 0; i <= returnValue.length - 1; i++){
//access your properties like this:
returnValue[i].ItemNumber;
returnValue[i].Description;
}
I don't know if using JsonResult will work like that, but if you return a list of objects in your server side code, it will work like that. Assuming you're using Asp.Net AJAX it will serialize automatically.
As far as I know there exists also the following json deserializer in Asp.net Ajax:
Sys.Serialization.JavaScriptSerializer.deserialize(...)
You'd have to browse for the exact usage since I don't know it by heard now.
I use the AJAX.NET function Sys.Serialization.JavaScriptSerializer.deserialize to get my JSON data when I've created it using System.Web.Script.Serialization.JavaScriptSerializer.Serialize.

Resources