How can I read JSON in ASP.NET? - asp.net

I need a simple method to read the results from Amazon Affiliates URL, I have the code for Amazon and I get a JSON result which I cannot read in ASP.NET.
Is there an easy method to parse the JSON data in ASP.NET 4.5 ?

You could also use the .NET built-in JavaScriptSerializer:
using System.Web.Script.Serialization;
...
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic obj = js.Deserialize<dynamic>(jsonString);

You can use JObject class based on Json.net
Link : http://james.newtonking.com/pages/json-net.aspx
For parsing you can use JObject.Parse Method
Code
var jsonString = #"{""Name"":""Aghilas"",""Company"":""....."",
""Entered"":""2012-03-16T00:03:33.245-10:00""}";
dynamic json = JValue.Parse(jsonString);
// values require casting
string name = json.Name;
string company = json.Company;
DateTime entered = json.Entered;

Use JSON.NET package, its great and simple.
To install the package:
Open the console. "View" > "Other Windows" > "Package Manager Console"
Then type the following:
Install-Package Newtonsoft.Json
You can both read the Json object as dynamic object or as strongly-typed one.
In case you want to read the Json type as a strongly typed object, you can do the following:
The class to populate the data:
public class AmazonAffiliate
{
public string Username {get;set;}
public string Email {get;set;}
public Date BirthDate {get;set;}
}
Method for converting Json strings to strongly-typed class:
public static T GetJsonContent<T>(string jsonAsString)
{
var serializer = new JsonSerializer<T>();
return serializer.DeserializeFromString(jsonAsString);
}
And you can use it like this:
AmazonAffiliate affiliate = GetJsonContent<AmazonAffiliate>(jsonString);

Related

Array in Api's Query String

Using WebClient do send an array to an ApiController via query string I get the error 400.
The api method looks like
public IHttpActionResult List([FromUri] Model model)
In the Model class I have
public int[] Ids { get; set; }
In the client side the code looks like:
webClient.QueryString.Add("ids", "1");
webClient.QueryString.Add("ids", "2");
...
await webClient.DownloadStringTaskAsync(url);
If I send just one "ids" parameter the code works fine, but not with two or more.
I found that the client creates the url like "url?ids=1,2" instead "url?ids=1&ids=2".
Is there some configuration I missed?
WebClient will automatically turn multiple values with the same key into a comma separated string. You can change this behavior, see: How to build WebClient querystring with duplicate keys?
I would recommend using HttpClient instead of WebClient though.

Exclude property from json serialization in ApiController

I am trying to exclude properties from being serialized to JSON in web ApiControllers. I have verified the following 2 scenarios work.
I have included the following attributes on the property I wish to exclude.
[System.Web.Script.Serialization.ScriptIgnore]
[System.Xml.Serialization.XmlIgnore]
If I manually serialize my object using the JavaScriptSerializer, the property is excluded. Also, if I view the serialized XML output from the web ApiController, the property is excluded. The problem is, the serialized JSON via the web ApiController still contains the property. Is there another attribute that I can use that will exclude the property from JSON serialization?
UPDATE:
I realized all my tests were in a much more complex project and that I hadn't tried this in a an isolated environment. I did this and am still getting the same results. Here is an example of some code that is failing.
public class Person
{
public string FirstName { get; set; }
[System.Web.Script.Serialization.ScriptIgnore]
[System.Xml.Serialization.XmlIgnore]
public string LastName { get; set; }
}
public class PeopleController : ApiController
{
public IEnumerable<Person> Get()
{
return new[]
{
new Person{FirstName = "John", LastName = "Doe"},
new Person{FirstName = "Jane", LastName = "Doe"}
};
}
}
Here is the generated output.
JSON:
[
{
"FirstName" : "John",
"LastName" : "Doe"
},
{
"FirstName" : "Jane",
"LastName" : "Doe"
}
]
XML:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<FirstName>John</FirstName>
</Person>
<Person>
<FirstName>Jane</FirstName>
</Person>
</ArrayOfPerson>
Be aware that JSON serialization is changing in Web API.
In the beta release, Web API used DataContractJsonSerializer to serialize JSON. However, this has changed; the latest version of Web API uses json.net by default, although you can override this and use DataContractJsonSerializer instead.
With DataContractJsonSerializer, you can use [DataContract] attributes to control the serialization. I'm stil not very familiar with json.net, so I don't know how it controls serialization.
You can use [JsonIgnore] attribute for a JSON-specific fix; or you can use [DataContract] and [DataMember] for a fix that works both with the JSON formatter, and with the (XML) DataContractSerializer.
This article provides more detailed info on the default media-type formatters:
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter
This is a little late to the game, but IgnoreDataMember is precisely what we need in your/my scenario:
[System.Runtime.Serialization.IgnoreDataMember]
public int NotSerialized { get; set; }
According to the MSDN, IgnoreDataMember came in with .NET 3.0 SP2.
JsonIgnore modifies the entire class definition. In case you want to control specific action/request, you can try this approach.
Looks like this covers what I need. It shows you you can swap out formatters. It even includes an example formatter that uses the JavaScriptSerializer which is what I need.
http://wildermuth.com/2012/2/22/WebAPI_for_the_MVC_Guy

How do SOAP headers work in ASMX Web Services?

I have a project that uses an asmx file with [WebMethods] and [SoapHeader("Auth")]. I have no experience using SOAP and don't understand how it works yet.
Going through the code I noticed that you can use a variable with the same name as the header and it contains the data. How is the data sent to the header? Where does it come from?
The data is sent in header by making use of a class that derives from SoapHeader. This class will be declared as a property in your webservice class. Then in your web method you will check the authentication information in this property before processing the actual method.
A simple implementation can be found here http://www.codeproject.com/KB/cpp/authforwebservices.aspx
The following msdn link tells about another similar technique, which would be more sophisticated one http://msdn.microsoft.com/en-us/library/9z52by6a.aspx.
Basic idea behind passing data in header remains same.
The data comes from XML within the <soap:Header> section of the SOAP envelope.
Create a class for your soap header like normal.
public class AuthHeader : SoapHeader
{
public string CompanyID;
public string Username;
public string Password;
}
Then within your normal class had the reference.
public class MyClass : WebService
{
public readonly AuthHeader authHeader;
[SoapHeader("authHeader", Direction = SoapHeaderDirection.In)]
[WebMethod(CacheDuration = 20
, EnableSession = true
, Description = "Find stuff now."
, MessageName = "FindStuff")]
[ScriptMethod(UseHttpGet = false
, ResponseFormat = ResponseFormat.Xml
, XmlSerializeString = true)]
public MyResponseClass FindStuff(string searchString)
{
MyResponseClass myResponseClass = new MyResponseClass();
if (authHeader.Username == "myUser" &&
authHeader.Password == "myPass" &&
authHeader.CompanyID == "BobsTire")
{
....
myResponseClass = ....
}
return myResponseClass;
}
}

How to consume COM object in ASP.NET class file

I have a COM object that I am trying to wrap in a C# class in order to make it more readily available for other applications that wish to consume it.
I have the following code that creates an instance of the COM object, and then using reflection makes a call to a method to retrieve user data. This code works fine when it is located in an aspx page.
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
However, when I move the code to a class file (JD_API.cs) in order to abstract it from the actual website, I can no longer get it to work. For example, I have the following static method that is declared like such:
public static string GetUserName() {
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName",
System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
Unfortunately, the Server object is restricted to some ASP.NET libraries that are included by default in web applications, and so the above code was a no-go. So at this point I decided to try to create an instance of the COM object like such:
public static string GetUserName() {
Type type = Type.GetTypeFromProgID("jd_api.UserCookie");
object jdObj = Activator.CreateInstance(type);
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
However at runtime I get an error that says, "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.".
I'm not sure where to go from here. Any help on how to abstract creating an instance of this COM object to a layer that is not within the web application itself would greatly appreciated. Thanks!!
Declare DLL functions within a class. Then define a static method for each DLL function you want to call.
The following code sample creates a wrapper named Win32MessageBox that calls the MessageBox function in User32.dll each time a .NET app calls the object Show method.
It requeres the System.Runtime.InteropServices namespace.
using System;
using System.Runtime.InteropServices;
class Win32MessageBox
{
[DllImport("user32.dll")]
private static extern int MessageBox(IntPtr hWnd, String text,
String caption, uint type);
public static void Show(string message, string caption)
{
MessageBox(new IntPtr(0), message, caption, 0);
}
}
To call it, just type:
Win32MessageBox.Show("StackOverflow!", "my stack box");
The method where you call the above line doesn't need to be aware that it's a actually calling a function in an unmanaged DLL.
Resources: the MCTS Self-Paced Training Kit (Exam 70-536) by Tony Northrup.
Hove you tried usinsing interoperating
I've done the following in the past (working from memory so you might need to fiddle with this a bit):
Right Click "References" in your project
Select "Add Reference"
Selelct the "Com" Tab
Find and add your Com Instnace
In your class file
using yourComName;
public static string GetUserName()
{
yourComName.yourComClass jdObj = new yourComClass();
string username = jdObj.GetUserName(someParameters);
return username;
}
Hope this a) works and b) helps!

Deserialize JSON Objects in Asp.Net MVC Controller

I'm trying to deserialize an object which was generated by LinqToSql. The user is allowed to edit the data of the object in the view and then it gets posted back to the controller. The edited Data comes in JSON. How does this action have to look like?
Something like...
public ActionResult(JsonObject json)
{
MyClass c = Jsonify(json) as MyClass;
}
Is there a nice helpful static class in the framework I'm missing? Or do I have to create a DataContract?
Many thanks
System.Web.Script.Serialization.JavaScriptSerializer
public ActionResult Blah(JsonObject json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
var c = js.Deserialize<MyClass>(json);
return View(c);
}
EDIT: Oops...just noticed you are passing an object instead of string....so you will need to use System.Runtime.Serialization.Json.DataContractJsonSerializer:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass c = (MyClass)serializer.ReadObject(json);

Resources