System.OutOfMemoryException with JSON.NET - json.net

Tried this with JSON.NET 6.0
DataSet ds = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>
("{\"tab1\":[{\"col1\":\"val1\"}]}"); // OK
DataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>
("{\"col1\":\"val1\"}"); // System.OutOfMemoryException
why?
thank you

IMO it's a bug, But if you want to deserialize DataSet or DataTable this might help you.

The JSON in your second example represents a only a single row of data, not a DataTable. A DataTable is an ordered collection of DataRows, therefore it needs to have square brackets in the JSON. Try it like this instead:
string json = "[{\"col1\":\"val1\"}]";
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
I am not sure why you are getting an OutOfMemoryException; I get a JsonSerializationException when I try it, as I would expect. Perhaps this was a bug that was fixed in the most recent version of Json.Net.

I have over come with this issue by creating JsonSerializer object. My code is as given below.
using (StreamReader r = new StreamReader(yourfilePath))
{
using (JsonReader reader = new JsonTextReader(r))
{
JsonSerializer serializer = new JsonSerializer();
T lstObjects = serializer.Deserialize<T>(reader);
}
}
Here yourfilePath :- is your file current full path
T :- is your object name, whether it could be Dataset, DataTable or any custom Object.

Related

gridview is not showing data properly

while trying to get data from https://blockchain.info/ticker in my grid view, i'm finding the result in single coloumn whether i want it in different coloumn.
i'm showing you my code and please give me a soloution.
public void ticker()
{
WebClient webClient = new WebClient();
dynamic result =webClient.DownloadString("https://blockchain.info/ticker");
GridView1.DataSource = result;
GridView1.DataBind();
}
[https://i.stack.imgur.com/nPjgS.jpg]
It looks like your results in JSON format so you have to convert in the proper format to display well in GridView.
import Newtonsoft.Json
dynamic result =JsonConvert.DeserializeObject(
webClient.DownloadString("https://blockchain.info/ticker"));
I hope it's help you, you can search more about it
thanks

How do I add a Dictionary<string,string> to an existing JSON.Net's JObject?

I've got a JObject (using JSON.Net) that I created by parsing some JSON text. I'm directly manipulating, adding keys at the top level of this JObject. I have no problems when the value I'm adding is a string:
json["newkey"] = "New Value"; // works
But I'll be damned if I can figure out how to add a Dictionary, e.g.:
Dictionary<string,string> dict = new Dictionary<string,string>();
dict["one"] = "1";
dict["two"] = "2";
json["dict"] = dict; // fails
I've done quite a bit of googling and reading the JSON.Net docs, but everything seems oriented towards reason JSON text into a JObject, or writing .NET objects as JSON text using serialization. Or using some fancy LINQ statements to do all kinds of things with complex objects...
I've tried these and none have worked:
json["dict"] = new JObject(dict);
json["dict"] = new JObject((Dictionary<string,string>)dict);
json["dict"] = new JArray(dict); // desperation sets in :)
json["dict"] = (JObject)dict; // please dear god let this work
Most of the latest errors I encounter are:
Could not determine JSON object type for type System.Collections.Generic.KeyValuePair`2[System.String,System.String].
I believe that you are looking for something like this:
json["dict"] = JObject.FromObject(dict);
There is a desperate "hack" that you can use, it's not pretty (doing twice the same thing) but it works :)
json["dict"] = JObject.Parse(JsonConvert.SerializeObject(dict));

How can i extract XML and use it as a datasource?

I am using asp.net VB and I have an XML file containing a set of data, I would like to use it in something like a datalist and where usually you would use a database i would like to use the XML file to produce the information.
Does anyone know how to do this, i have read about transform files but surely i will format the information in the control?
The file has multiple records so in some cases i would need to perform queries on the information through the datasource.
I would maybe look into XML serialization and de-serialization. Using de-serialization you could read your XML into a List(T) object containing a list of your own class objects and use that as a data source for your application.
Heres a link that you may find useful:
http://msdn.microsoft.com/en-us/library/ms731073.aspx
Hope this helps.
Dim ds As New DataSet()
ds.ReadXml(MapPath("data.xml"))
First you have to parse the XML and store that into custom C# object or you can directly pass the XML to your stored procedure and do the codding there for saving it into DB.
Passing the xml to stored procedure and manipulating it there is bit difficult so what I suggest is to parse it in C# and then get a custom object. Once you get it you can do whatever you want to.
Below is the sample code that parse a XML file and generate a custom C# object from it.
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}

How do we use SqlDataReader obejct as an array?

It might sound kiddish or silly but i wanna know that in codes like..
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[1]. ToString());
how do we use the SqlDataReader object as an array (rdr[1]) without declaration?
What I want to know is, what is happening in the following line?
Response.Write(rdr[1].ToString());
Since rdr is an object, how art we able to use square brackets with that?
You are looking for Indexers.
Please refer to this link.
Indexers are a syntactic convenience
that enable you to create a class,
struct, or interface that client
applications can access just as an
array
ref: http://msdn.microsoft.com/en-us/library/2549tw02.aspx
you can do something like this.
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
Console.WriteLine("reader.GetValues retrieved {0} columns.",
fieldCount);
for (int i = 0; i < fieldCount; i++)
Console.WriteLine(values[i]);
Console.WriteLine();
No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method). So you cannot directly convert it to array type. You need to convert it to list.
It sounds like using a generic list and then returning the list as an array would be a good option. For example,
List list = new List();
while (rdr.Read())
{
list.Add(rdr.GetInt32(0));
}
return list.ToArray();

Error in ASP.NET C# (implicit conversion)

I am new in ASP.NET programming. Please help me.
void DisplayData()
{
DataTable dt = new DataTable();
//objBuyer.BuyerId = Convert.ToInt64(Request.QueryString["id"]);
**ERROR-->>>** dt = objBuyer.DisplayData();********
if (dt.Rows.Count > 0)
{
txtBName.Text = dt.Rows[0][1].ToString();
ERROR:Cannot implicitly convert type 'void' to 'System.Data.DataTable'
You are trying to convert void to a DataTable, which is not possible. Your method has to return a DataTable for this to work.
The problem is that the DisplayData method does not return a DataTable object, it simply displays the data in objBuyer, and returns void.
That's the problem, but I can't really help further than that without some sort of context!
The DisplayData() method needs to return a DataTable in order for this to work.
A nice and easy tutorial can be found here: http://www.aspnettutorials.com/tutorials/controls/data-table-csharp.aspx
As you can see, there's a DataTable created and after that's done, several rows are added to the table with the Rows.Add() method.

Resources