Can Web API convert XML into Json? - asp.net

I've got a legacy web service which I'd like to wrap with a new MVC Web API, question is can I get the ASP.NET Web API to convert my xml into json?
A thought that I had was to use XDocument to create a dynamic object and return that, but when I tried it with an ExpandoObject unfortunately it returned a json object with Key/Value pairs.

Using json.NET you can do it easily:
string result = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmldocument);
Download Newtonsoft.Json at http://james.newtonking.com/pages/json-net.aspx

You could. One way to do it would be to deserialize the XML into objects and then serialize them again into JSON.
A more efficient (though harder to code up approach) would be to write your own xml-to-json "transcriber" that reads in the XML and spits out JSON.
Just note that not all XML can be represented easily as JSON.

Turns out this can be done by converting an XDocument to a dynamic JsonObject like so roughly:
var doc = XDocument.Load(uri);
foreach (var node in doc.Root.Descendants()) {
var obj = (dynamic) new JsonObject();
foreach (var child in node.Descendants())
{
obj[child.Name.LocalName] = child.Value;
yield return obj;
}
}

In WebApiConfig file inside Register function add the below code at last (WebApiConfig file is at App_Start folder)
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

config.Formatters.Remove(config.Formatters.XmlFormatter);

Related

returning a JSON formatted file via WCF

We've seen a number of posts relating to JSON data returns via WCF, but they all cover the aspect of converting object to JSON and then returning that object converted to JSON via the magic of attributes.
We've got a number of preformatted JSON files that we want to return via an WCF service. Essentially all we need to do is read the files in (or a cached copy of of the file) and then return the data as a string . I think ... It seems wasteful to read in the JSON file, serialize it to an object then deserialize back to JSON.. Any help on this?
When using the WebHttpBinding, this is as simple as creating a WebGet annotated method with a Stream return type:
[WebGet]
public Stream GetFile(Int32 someId)
{
//your logic to lookup or create the file here.
//Open the file (a MemoryStream would be acceptible as well if you were creating the data on the fly
Stream stream = File.OpenRead(yourFilePath);
//register an event to clean up the temporary file (if necessary)
OperationContext.Current.OperationCompleted += (s, e) =>
{
File.Delete(yourFilePath);
};
return stream;
}

Convert Results of LINQ to SQL Query to XML/JSON

I wish to populate a JavaScript array with the results of a database query. From what I understand, a good approach is to populate a bunch of directories on my server with serialized XML or JSON files which my JS functions can then read into without having to access the database. Is this true? Should the database write these XML files upon user interaction, or should they be prepopulated?
From the details you have provided:
I Personally would create a Web Service endpoint returning your linq query serialized to JSON using JSON.NET or an equivalent. The endpoint can then be called using ajax within your client page.
You can check this example out on ASP.NET for how to create a asmx (legacy) web service. Also you can look at this example of using the [WebMethod] attribute .
A web method in your code behind files.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMyQueryResultsAsJson()
{
var results = GetQueryResults();
var jss = new JavaScriptSerializer();
string json = jss.Serialize(results);
return json;
}
A ajax call on your client page:
function loadData() {
var myArray = [];
$.getJSON("<%= ResolveUrl("~/MyPage.aspx/GetMyQueryResultsAsJson") %>", function (data) {
$.each(data, function(obj) {
myArray.push([obj.id, obj.someValue, obj.AnotherValue]);
});
});
}
I used jQuery ajax with generic http handler returing json
I created handler and put my business logic there.
It return me the result in form of json
I iterated the json using jquery.
And created my html form that.
Edit 1
Here are some useful links
http://www.codeproject.com/Articles/203621/Call-HTTPhandler-from-jQuery-Pass-data-and-retriev
http://www.sharepointnutsandbolts.com/2010/11/sp2010-ajax-part-4-returning-json-from.html
Edit 2
You can also take benefit of jtemplate
http://www.joe-stevens.com/2010/01/05/using-the-jtemplate-jquery-plugin-with-ajax-and-asp-net/
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

Cannot upload a file to a webservice and get the response in Json format

I have a simple webservice that I would like to upload a file to. The problem is that I need the response in json.
Form my experience in order to get a response in Json my request has to have a content-type of 'application/json'. But ofcourse this cannot be the case with a file upload since the content type will have to be 'multipart/form-data'.
In my Json i want to return a value showing whether successful and a filename.
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public TyoeOfSomeObject UploadFile()
{
// Get the file from the context and do something with it
HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files[0];
// Return either a string or an object to serialise with the required values
return SomeObject;
}
I was having the same issue, and resolved it by setting the response's ContentType and calling the response's Write() function:
C#
String j = jsonParser.AsJson(obj);
Context.Response.ContentType = "application/json; charset=utf-8";
Context.Response.Write(j);
VB
Dim j As String = jsonParser.AsJson(obj)
Context.Response.ContentType = "application/json; charset=utf-8"
Context.Response.Write(j)
You could set the return type of your function to a string and then use some JSON serializer to serialize your object to JSON and return it as a JSON string. For JSON serialization I use Jayrock I believe ASP .NET has its own JSON libraries now as well.
You can declare your web method with byte[] as an output parameter. Then you can set ContentType and return any data you want.
If you use WCF instead of ASMX web service you can return Stream or Message in such cases (see Returning raw json (string) in wcf. You can try also return Stream instead of byte[] in the web service if your file is very large. Probably it will also works with ASMX web service.
ASP.Net Webservice Serialization
I was unable to find a way to return a response in json. I don't think its possible without tinkering with the inner workings. The solution I used was to create an aspx that could handle the file, you could ofcourse use .ashx or WCF as described by OLEG.

Returning JSON object from an ASP.NET page

In my particular situation, I have a couple of solutions to my problem. I want to find out which one is more feasible. In this case, I can also achieve my goal by returning a JSON object from my server side code; however, I do not know how it is done and what the best way of doing it is.
First off, I don't need a full aspx page as I only need a response returned from code. So, do I use web services, a handler, or is there any other specific way to do this?
Is this solution feasible? Do I build the JSON string using the StringBuilder class and inject that string into the target aspx page? Are there any precautions or things that I should be aware of?
I appreciate your ideas.
Regards,
Kemal
------------UPDATE !------------
Suppose I have a JSON object in my userlist.aspx page, which then I use with jQuery...
{"menu": {
"id": "color1",
"value": "color",
"popup": {
"menuitem": [
{"value": "Red"},
{"value": "Green"},
{"value": "Yellow"}
]
}
}} // example taken from the json.org/example page
Now when I want to add a new menu items from my aspx page, what do I do... I think this way my question is more specific...
Lets assume I create a new string in my aspx code, as such "{"value": "Blue"}. How do I inject this into the already existing itemlist in the target page? Or is this not the correct approach to this kind of situation? If not, how else can it be achieved?
Also, if I wanted to fire a jQuery event when a new item is added to this list, how is this achieved?
------------UPDATE 2 on 26 August 2015 ------------
By the time I asked this question, the way I was approaching the problem was in another aspect. I am now more proficient in the subject and can gladly accept the most voted answer since the approach to this question clearly should not include the already existing JSON and output a new one from the code as #DavGarcia also suggests.
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.
var json = Json.Encode(new {
orientation = Cache["orientation"],
alerted = Cache["alerted"] as bool?,
since = Cache["since"] as DateTime?
});
Response.Write(json);
If you get code behind, use some like this
MyCustomObject myObject = new MyCustomObject();
myObject.name='try';
//OBJECT -> JSON
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string myObjectJson = javaScriptSerializer.Serialize(myObject);
//return JSON
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myObjectJson );
Response.End();
So you return a json object serialized with all attributes of MyCustomObject.

Is there a built in way in .Net AJAX to manually serialize an object to a JSON string?

I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <System.Web.Services.WebMethod()> and <System.Web.Script.Services.ScriptMethod()> attributes so there must be a built-in way that I'm missing.
PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.
This should do the trick
Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
I think what you're looking for is this class:
System.ServiceModel.Web.DataContractJsonSerializer
Here's an example from Rick Strahl: DataContractJsonSerializer in .NET 3.5
Since the JavaScriptSerializer class is technically being deprecated, I believe DataContractJsonSerializer is the preferable way to go if you're using 3.0+.
Well, I am currently using the following extension methods to serialize and deserialize objects:
using System.Web.Script.Serialization;
public static string ToJSON(this object objectToSerialize)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(objectToSerialize);
}
/// <typeparam name="T">The type we are deserializing the JSON to.</typeparam>
public static T FromJSON<T>(this string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Deserialize<T>(json);
}
I use this quite a bit - be forewarned, this implementation is a bit naive (i.e. there are some potential problems with it, depending on what you are serializing and how you use it on the client, particularly with DateTimes).
In the System.Web.Extensions assembly, version 3.5.0.0, there's a JavaScriptSerializer class that should handle what you want.
Try
System.Web.Script.Serialization.JavaScriptSerializer
or Check out JSON.org there is a whole list of libraries written to do exactly what you want.

Resources