asp.net parse json array - asp.net

I write this code for read json in httphandler:
var jsonSerilizer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
and my json string is:
{"r_id":"140","name":"d","count":"5","c_id":"150"}
and i use this method for parse json string:
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(object));
string r_id = a["r_id"];
string Name = a["name"];
string count = a["count"];
string c_id = a["c_id"];
up code parse my json string to :
r_id:140
name:d
count:5
c_id:50
When client send me array of string json for example :
{"r_id":"140","name":"d","count":"5","c_id":"150"}
{"r_id":"150","name":"der","count":"50","c_id":"150"}
i can parse up json string
How can i?
I use this code:
var jsonSerilizer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
File.AppendAllText(#"d:\status\LOL.txt", "GetJSON to FROM:"+ jsonString+"\r\n", Encoding.UTF8);
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));
foreach (var obj in a)
{
File.AppendAllText(#"d:\status\LOL.txt", obj.name + "\r\n", Encoding.UTF8);
}
but when program recieve to File.AppendAll.. program crash and down.

First of all try to create a model ( class to hold your objects) like this :
Class ClientMessage {
public string r_id {get;set;}
public string name {get;set;}
public string count {get;set;}
public string c_id {get;set;}
}
In this case you would receive a List , so try to do it like this :
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic a = j.Deserialize(jsonString, typeof(List<ClientMessage>));
// and then iterate on your object
foreach (var obj in a)
{
//start assigning values
}

I would suggest creating an object you can parse your JSON into, so something like:
public MyClass {
public int r_id { get; set;}
public string name { get; set; }
// etc
}
This will allow you to parse directly into that object, like this:
var results = j.Deserialize<List<MyClass>>(jsonString);

Can you try something this code, I am assuming you are getting json data like below.
[
{
r_id: "123",
name: "deepu",
count:"5",
c_id:"150"
},
{
r_id: "444",
name: "aaa",
count:"25",
c_id:"55"
},
{
r_id: "5467",
name: "dfgdf",
count:"5",
c_id:"3434"
}
]
I am using the above Client Message class here and adding JsonProperty attribute.
public class ClientMessage
{
[JsonProperty("r_id")]
public string RId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("count")]
public string Count { get; set; }
[JsonProperty("c_id")]
public string Cid { get; set; }
}
Finally, get the json data fort testing, I am reading the data from external file..
var data = System.IO.File.ReadAllText("jsondata.txt");
var jsResult = JsonConvert.DeserializeObject<List<ClientMessage>>(data);
NOTE : You need to add Newtonsoft.Json reference in your project

Related

How to separate JSON Data In ASP.NET Console Application?

I Create a one web API. its main aim is a request to another server and get the response from that server.
I successfully get the response for a particular server.
I get the response(its a JSON Format) is below.
{
"id": "test#gmail.com",
"active": 1,
"is_logged": true,
"token": "hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh",
"status": "OK",
"usertype": "TestUser",
"msg": "Login Successfull."
}
I try to separate using split function
string[] sep = response.Split(',');
foreach (string any in sep)
Console.WriteLine(any);
//string[] colon = sep[0].Split(':');
string[][] colon = sep.Select(x => x.Split(':')).ToArray();
//int count = colon.Count();
for (int i = 0; i <= colon.Length; i++)
{
Console.WriteLine(colon[i][0]);
Console.WriteLine(colon[i][1]);
}
Any other way to separate the response? I also use all the field in some other purpose.
Create a Class based on your response property:
public class UserData
{
public string id { get; set; }
public int active { get; set; }
public bool is_logged { get; set; }
public string token { get; set; }
public string status { get; set; }
public string usertype { get; set; }
public string msg { get; set; }
}
On reading the response data, use JsonConvert.DeserializeObject
string response = "{\"id\":\"test #gmail.com\",\"active\":1,\"is_logged\":true,\"token\":\"hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh\",\"status\":\"OK\",\"usertype\":\"TestUser\",\"msg\":\"Login Successfull.\"}";
var responseData = JsonConvert.DeserializeObject<UserData>(response);
//here the print in JSON Data
Console.WriteLine("id : " + responseData.id);
Console.WriteLine("active : " + responseData.active);
Console.WriteLine("is_logged : " + responseData.is_logged);
Console.WriteLine("token : " + responseData.token);
Console.WriteLine("status : " + responseData.status);
Console.WriteLine("usertype : " + responseData.usertype);
Console.WriteLine("msg : " + responseData.msg);
use Newtonsoft.json.dll by adding the NuGet package,
Then convert the response to json object
JObject jo = JObject.Parse(searchCondition);
foreach (JToken child in jo.Children()) {
var prop = child as JProperty;
if (prop.Value != null && !string.IsNullOrEmpty(prop.Value.ToString())) {
string name=prop.Name;
string value = prop.Value;
//You can now do whatever with the values like put in a list of object
}
}
This is My own example to get the properties from JSON string, you can use this.
But first, you need to install this package:-> Newtonsoft.Json.Linq to access JObject
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonString = "{\"firstname\":\"Alex Wu\",\"lastname\":\"type\"}";
JObject jObject = JObject.Parse(jsonString);
string firstname = (string)jObject.SelectToken("firstname");
string lastname = (string)
Console.WriteLine("{0}", firstname);
Console.ReadLine();
}
}

Json.net , JsonConvert gives me an error during deserialization: not generating an object instance

I’m sending from an asp.net page Json data from javascript, the JS data/object was previously serialized and the sent to my asp.net genericHandler.ashx page.
On server side I’m using Json.net, this is my code in the generic handler:
public void ProcessRequest(HttpContext context)
{
int numberOfFiles = 0;
MyGlobalSettings myGlobalSett = new MyGlobalSettings();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string jsonString = string.Empty;
context.Request.InputStream.Position = 0;
using (StreamReader inputStream = new System.IO.StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
MyData contentType = new MyData();
contentType = jsonSerializer.Deserialize<MyData>(jsonString);
Debug.WriteLine("Context 1:" + contentType.name);
context.Request.InputStream.Position = 0;
string json;
using (var reader = new StreamReader(context.Request.InputStream))
{
json = reader.ReadToEnd();
}
MyData contentType2 = new MyData();
contentType2=JsonConvert.DeserializeObject<MyData>(json);
Debug.WriteLine("Context 2:" + contentType2.name);
My deserialized object class
public class MyData
{
public string name { get; set; }
public string lastName { get; set; }
public string age { get; set; }
}
This is the error I get.
An exception of type 'System.NullReferenceException' occurred in Demo_xss_prevention_04.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
I've tried the built in .net Json serializer (JavaScriptSerializer), and it works, but with Json.net I get this error. How can I fix it?

XML File Model Mapping asp.net MVC3 ( Dynamically Map an xml file to a model class asp.net mvc3 )

I am trying to implement a payment gateway(INTUIT payment gateway). I would like to serialize an xml to an model class and save into my database. I am using Desktop Model for intuit payment gateway, as the hosted model is a pain to get working with especially ssl certificates, so i dont want to try that.
I must mention i am able to get the response using the below mentioned code, where i am stuck at the moment is serialize the xml and save the response into the database. This xml is pulled from a folder in my xmlfiles folder located in my project.
For sample xml format, check out this one. https://ipp.developer.intuit.com/0085_QuickBooks_Windows_SDK/qbms/0060_Documentation/Sending_Requests
this is an xml file i am trying to post to url (https://merchantaccount.ptc.quickbooks.com/j/AppGateway)
<?xml version="1.0"?>
<?qbmsxml version="4.5"?>
<QBMSXML>
<SignonMsgsRq>
<SignonDesktopRq>
<ClientDateTime>2012-07-25T17:13:45</ClientDateTime>
<ApplicationLogin>abc.abc.us</ApplicationLogin>
<ConnectionTicket>TGT-1-g42FGaMfOTQ82GcWFBpsuQ</ConnectionTicket>
</SignonDesktopRq>
</SignonMsgsRq>
<QBMSXMLMsgsRq>
<CustomerCreditCardChargeRq>
<TransRequestID>4540453787200</TransRequestID>
<CreditCardNumber>4111111111111111</CreditCardNumber>
<ExpirationMonth>12</ExpirationMonth>
<ExpirationYear>2016</ExpirationYear>
<IsCardPresent>false</IsCardPresent>
<Amount>10.00</Amount>
</CustomerCreditCardChargeRq>
</QBMSXMLMsgsRq>
</QBMSXML>
The Controller i use to make a post to the url
public ActionResult Index()
{
WebRequest req = null;
WebResponse rsp = null;
string fileName = Server.MapPath("~/XMLData/XMLFile1.xml");
string uri = "https://merchantaccount.ptc.quickbooks.com/j/AppGateway";
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "application/x-qbmsxml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
// var resp = (Object)rsp.GetResponseStream();
if (rsp != null)
{
StreamReader inStream = new StreamReader(rsp.GetResponseStream());
var data = inStream.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(data);
string path = Server.MapPath("~/XMLData/SampleXmlE2E.xml");
xmlDoc.Save(path);//regenerates the xml file in different system.
}
return View();
//XElement root = new XElement("root");
//root.Add(new XElement("element1"));
//root.Add(new XElement("element2"));
//root.Add(new XAttribute("attribute1", "a value"));
//return new XmlResult(root);
}
private string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
private string SendRequest(Uri UriObj, string data)
{
string _result;
var request = (HttpWebRequest)WebRequest.Create(UriObj);
request.Method = "POST";
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var streamResponse = response.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
_result = streamRead.ReadToEnd().Trim();
streamRead.Close();
streamResponse.Close();
response.Close();
return _result;
}
Any help would be appreciated. Thanks
Varun,
[Edit -update]
Based on this XML:
<?qbmsxml version="4.5"?>
<QBMSXML>
<SignonMsgsRq>
<SignonDesktopRq>
<ClientDateTime>2012-07-25T17:13:45</ClientDateTime>
<ApplicationLogin>app.app.login.url</ApplicationLogin>
<ConnectionTicket>TGT-1-g42FGaMfOTQ82GcWFBpsuQ</ConnectionTicket>
</SignonDesktopRq>
</SignonMsgsRq>
<QBMSXMLMsgsRq>
<CustomerCreditCardChargeRq>
<TransRequestID>4540453787200</TransRequestID>
<CreditCardNumber>4111111111111111</CreditCardNumber>
<ExpirationMonth>12</ExpirationMonth>
<ExpirationYear>2016</ExpirationYear>
<IsCardPresent>false</IsCardPresent>
<Amount>10.00</Amount>
</CustomerCreditCardChargeRq>
</QBMSXMLMsgsRq>
</QBMSXML>
Here's the class structure that you'd need to deserialize into as per the example above:
[XmlRoot("QBMSXML")]
public class QbmsXml
{
[XmlElement("SignonMsgsRq")]
public SignonMsgsRq SignonMsgsRq { get; set; }
[XmlElement("QBMSXMLMsgsRq")]
public QbmsXmlMsgsRq QbmsXmlMsgsRq { get; set; }
}
public class SignonMsgsRq
{
[XmlElement("SignonDesktopRq")]
public SignonDesktopRq SignonDesktopRq { get; set; }
}
public class SignonDesktopRq
{
[XmlElement("ClientDateTime")]
public DateTime ClientDateTime { get; set; }
[XmlElement("ApplicationLogin")]
public string ApplicationLogin { get; set; }
[XmlElement("ConnectionTicket")]
public string ConnectionTicket { get; set; }
}
public class QbmsXmlMsgsRq
{
[XmlElement("CustomerCreditCardChargeRq")]
public CustomerCreditCardChargeRq CustomerCreditCardChargeRq { get; set; }
}
public class CustomerCreditCardChargeRq
{
[XmlElement("TransRequestID")]
public Int64 TransRequestID { get; set; }
[XmlElement("CreditCardNumber")]
public string CreditCardNumber { get; set; }
[XmlElement("ExpirationMonth")]
public int ExpirationMonth { get; set; }
[XmlElement("ExpirationYear")]
public int ExpirationYear { get; set; }
[XmlElement("IsCardPresent")]
public bool IsCardPresent { get; set; }
[XmlElement("Amount")]
public double Amount { get; set; }
}
Just use the xmlSerialiser along the lines of:
class Program
{
private static T DeSerialize<T>(string fromXmlFile) where T: class
{
if (!File.Exists(fromXmlFile))
{
return default(T);
}
T deserializedClass;
var serializer = new XmlSerializer(typeof(T));
// ToDo: add error catching etc
using (var reader = new StreamReader(fromXmlFile))
{
deserializedClass = (T)serializer.Deserialize(reader);
}
return deserializedClass;
}
static void Main(string[] args)
{
var yourXmlFilePath = #"d:\temp\xmltest.xml";
var deserializedClass = DeSerialize<QbmsXml>(yourXmlFilePath);
Console.WriteLine(deserializedClass
.QbmsXmlMsgsRq
.CustomerCreditCardChargeRq.Amount);
Console.Read();
}
}
hope this helps.

XML De-serialization giving null WCF Objects

I am having an XML string like
<?xml version="1.0"?>
<FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AuthenticationInfo xmlns="http://www.usps.com/postalone/services/UserAuthenticationSchema">
<UserId xmlns="">FAPushService</UserId>
<UserPassword xmlns="">Password4Now</UserPassword>
</AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>
In Order to map the nodes with Class, i am having the class structure in WCF like
[DataContract]
[Serializable]
public class FullServiceAddressCorrectionDelivery
{
[XmlElement("AuthenticationInfo", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
[DataMember]
public AuthenticationInfo AuthenticationInfo { get; set; }
}
[DataContract]
[Serializable]
public class AuthenticationInfo
{
[DataMember]
[XmlElement("UserId", Namespace = "")]
public string UserId { get; set; }
[DataMember]
[XmlElement("UserPassword", Namespace = "")]
public string UserPassword { get; set; }
}
For De-serialization , i used xmlserializer to De-serialize the object
XmlSerializer xs = new XmlSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.Deserialize(stream);
this method returned me a Null FullServiceAddressCorrectionDelivery object..
but when i used DataContractSerializer .. like
DataContractSerializer xs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.ReadObject(stream);
then following exception came out..
Error in line 2 position 46. Expecting element 'FullServiceAddressCorrectionDelivery' from namespace 'http://schemas.datacontract.org/2004/07/WcfService1'.. Encountered 'Element' with name 'FullServiceAddressCorrectionDelivery', namespace ''.
i am stuck with this...
i somehow with the help of RENE(StackOverFlow member) succeded to deserialize if the class was in same project .. but when i converted them to WCF Datacontracts.. i came across that issue ..... please guide me where i am doing wrong here...
Depending on how you want to use the data contract serializer (DCS) for that input, you may or may not be able to do that. The namespace of the data members in the DCS are defined by the namespace of the contract to which they belong, unless it's the root element (in which case the [DC] namespace also defines the namespace of the element).
Your root element, FullServiceAddressCorrectionDelivery, has one namespace in your sample XML (empty), and its member, AuthenticationInfo, has another (http://www.usps.com/postalone...). That means that unless you actually change how the serializer is created, you won't be able to use the DCS for this type.
The XmlSerializer (XS), however, should work just fine - members of the type can have different namespaces. As you can see in the code below, I can post the XML you provided verbatim to an operation which takes the FullServiceAddressCorrectionDelivery as an input, and the object is properly populated - you need to mark the operation (or the contract) with the [XmlSerializerFormat] attribute to get this behavior.
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a
{
const string XML = #"<?xml version=""1.0""?>
<FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
<UserId xmlns="""">FAPushService</UserId>
<UserPassword xmlns="""">Password4Now</UserPassword>
</AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>";
[XmlRoot(ElementName = "FullServiceAddressCorrectionDelivery", Namespace = "")]
public class FullServiceAddressCorrectionDelivery
{
[XmlElement("AuthenticationInfo", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
[DataMember]
public AuthenticationInfo AuthenticationInfo { get; set; }
}
public class AuthenticationInfo
{
[XmlElement("UserId", Namespace = "")]
public string UserId { get; set; }
[XmlElement("UserPassword", Namespace = "")]
public string UserPassword { get; set; }
}
[ServiceContract(Namespace = "")]
public interface ITest
{
[XmlSerializerFormat]
[OperationContract]
FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input);
}
public class Service : ITest
{
public FullServiceAddressCorrectionDelivery Echo(FullServiceAddressCorrectionDelivery input)
{
return input;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
c.Headers[HttpRequestHeader.ContentType] = "text/xml";
Console.WriteLine(c.UploadString(baseAddress + "/Echo", XML));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
For completeness sake, this is how you'd change the serializer creation (passing the root name and namespace) to be able to deserialize the XML you provided using the data contract serializer.
public class Post_6fc3a1bd_b3ca_48da_b4d2_35271135ed8a_b
{
const string XML = #"<?xml version=""1.0""?>
<FullServiceAddressCorrectionDelivery xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<AuthenticationInfo xmlns=""http://www.usps.com/postalone/services/UserAuthenticationSchema"">
<UserId xmlns="""">FAPushService</UserId>
<UserPassword xmlns="""">Password4Now</UserPassword>
</AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>";
[DataContract(Name = "FullServiceAddressCorrectionDelivery", Namespace = "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
public class FullServiceAddressCorrectionDelivery
{
[DataMember]
public AuthenticationInfo AuthenticationInfo { get; set; }
}
[DataContract(Name = "AuthenticationInfo", Namespace = "")]
public class AuthenticationInfo
{
[DataMember]
public string UserId { get; set; }
[DataMember]
public string UserPassword { get; set; }
}
static string Serialize(object obj, bool useDataContractSerializer)
{
MemoryStream ms = new MemoryStream();
XmlWriterSettings ws = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
OmitXmlDeclaration = false,
Encoding = new UTF8Encoding(false)
};
XmlWriter w = XmlWriter.Create(ms, ws);
if (useDataContractSerializer)
{
var dcs = new DataContractSerializer(obj.GetType(), "FullServiceAddressCorrectionDelivery", "");
dcs.WriteObject(w, obj);
}
else
{
new XmlSerializer(obj.GetType()).Serialize(w, obj);
}
w.Flush();
string result = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(result);
w.Close();
ms.Close();
return result;
}
public static void Test()
{
Console.WriteLine("Serialization:");
MemoryStream ms = new MemoryStream();
XmlWriterSettings ws = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
OmitXmlDeclaration = false,
Encoding = new UTF8Encoding(false)
};
XmlWriter w = XmlWriter.Create(ms, ws);
var dcs = new DataContractSerializer(typeof(FullServiceAddressCorrectionDelivery), "FullServiceAddressCorrectionDelivery", "");
var obj = new FullServiceAddressCorrectionDelivery
{
AuthenticationInfo = new AuthenticationInfo
{
UserId = "FAPushService",
UserPassword = "Password4Now"
}
};
dcs.WriteObject(w, obj);
w.Flush();
string result = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(result);
Console.WriteLine();
Console.WriteLine("Deserialization:");
ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
var obj2 = (FullServiceAddressCorrectionDelivery)dcs.ReadObject(ms);
Console.WriteLine("{0} - {1}", obj2.AuthenticationInfo.UserId, obj2.AuthenticationInfo.UserPassword);
}
}

Create JSON object or string..?

Can we initialize JSON object with a string in C# ;
like: "Person": [{"age":"42","name":"John"}]
as object JsonData = "Person": [{"age":"42","name":"John"}];
???
So that i can give this JSON object directly to the DatacontractJSONSerializer
And i could get the data out of it.!
List<Person> people = new List<Person>{
new Person{age = 1, name = "Scott"},
new Person{age = 2, name = "Bill"}
};
string jsonString = ExtensionMethods.JSONHelper.ToJSON(people);
}
}
}
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
So,
string jsonString = ExtensionMethods.JSONHelper.ToJSON(people);
Gives a string of : [{},{}]
Empty data structure, Any idea..?
With extension methods, you want to patch your method onto the type that you intend to call that method against. In this case, IEnumerable is a good place to add methods you want to use on a List:
public class Person {
public int age { get; set; }
public string name { get; set; }
}
public static class JSONHelper {
public static string ToJSON(this IEnumerable obj) {
return new JavaScriptSerializer().Serialize(obj);
}
}
void Main() {
List<Person> people = new List<Person> {
new Person() { age = 1, name = "Scott" },
new Person() { age = 2, name = "Bill" }
};
// [{"age":1,"name":"Scott"},{"age":2,"name":"Bill"}]
string json = people.ToJSON();
}
The important distinction is that you should use the extension method against a variable of the type it's defined against. You shouldn't reference the extension method directly.

Resources