C# How to read Object - c#

i try to passing javascript array to code-behind using object in code-behind, now i should get each value
[System.Web.Services.WebMethod]
public static void getData(object[] data)
{
...
}
this is array from javascript :
var data = [["5","John"],["6","Marteen"]];
after i pass into code-behind :
data {object[137]}
--[0] {object[1]}
----[0] Count = 8
------[0] {[id, 5]}
------[1] {[Name, John]}
i have to get ID and Name, i can't simply read like javascript,
ex : data[0][0]["Name"] = "John";
now i just try to read using foreach and i still can't get the value
foreach (object[] item in data)
{
var array = (object[])item;
foreach (var str in array)
{
/*how to get the value*/
}
}
so how should i do to get that value using index?
thanks before

JavaScript array in server-side is nothing but a plain string. Its unstructured data. To get your object structure back you need to define corresponding C# class. and then as Sayse suggested use Json serializer, something like JSON.NET http://www.newtonsoft.com/json.

Related

How to find particular json element from txt file in c# using xpath/jsonpath?

I have a lot of JSON format data into text file and format is like:
[{"ev":"AM","sym":"TMHC","v":1000,"av":74917,"op":18.92,"vw":19.1305,"o":19.13,"c":19.15,"h":19.15,"l":19.13,"a":19.143,"z":90,"n":1,"s":1549380300000,"e":1549380360000},{"ev":"AM","sym":"SPYG","v":7103,"av":184266,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000},
{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}]
So I need to find json element of particular symbol. Like if I use AAPL then it gives us all AAPL element data from txt file. Like
{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}
So please can you help me to how should I make it ?
static void xPathUsing()
{
const string filePath = #"D:\Aggregate_Minute_AAPL.txt";
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
}
}
As you need to run multiple operations on the data, the best way would be to read the data into memory once (or again whenever the data changes) and hold them in a way that supports fast querying. In order to find a row by the symbol, you could create a dictionary that holds the data.
The following samples use the widely used JSON.NET library for parsing the JSON.
First, you need to define a class that ressembles the schema of your JSON objects, e.g.:
class Row
{
[JsonProperty("sym")]
public string Symbol { get; set; }
public decimal vw { get; set; }
// ...
}
Please note that you can use the JsonProperty attribute in order to be able to assign different names to the properties of the class than in the JSON.
The following sample shows how to read the data from a file and how to convert it to a dictionary:
var input = File.ReadAllText("C:\\Temp\\abc.json");
var rows = JsonConvert.DeserializeObject<IEnumerable<Row>>(input);
var dict = rows.ToDictionary(x => x.Symbol, x => x, StringComparer.OrdinalIgnoreCase);
After preparing your dictionary once, you can get the corresponding row by using the indexer:
var aaplRow = dict["AAPL"];

Unable to perform for loop on json response object

I have dictionary of categories & their types in .cs file such as
Dictionary<string, List<string>> jsonDic
I have converted it into the json object string using following logic:
JavaScriptSerializer jss = new JavaScriptSerializer();
string barJson = jss.Serialize(jsonDic);
string js = "TypesArray(" + barJson + ")";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup1", js, true);
Now, in .js file I am getting following response
As we can see result is not in the form of array I am not able to index tpoints since it is not an array. What should I do? I want to index categories also types assosiated with each category..
You can access any of the attributes by name
tpoints["Foods"]
and that returns you an array of strings, in the foods case
[Restaurant, Cafe, Bakery]
If you want to iterate,
for (var property in tpoints ) {
if (tpoints.hasOwnProperty(property)) {
// do stuff
}
}
I think you are getting very confused with the kind of data structure you're working with. First, you're question title is false...
Unable to perform for loop on json response object
because you are indeed looping through the json objects. When you serialize the object below...
Dictionary<string, List<string>> jsonDic;
the serializer is actually mapping each KeyValuePair object inside the dictionary to a json array item, that is tPoint. So, to iterate through this array all you have to do is the following...
for (var tpoint in tpoints ) {
tpoint.Foods; //get food array
tpoint.Foods[0]; //get the first food item
}
and so on, you could even add a nested for loop to iterate through each inner array as below...
for (var tpoint in tpoints ) {
for(var i = 0; i < tpoint.Foods.length;i++){
console.log(tpoint.Foods[i]);
}
}
this will iterate through all food items in every tpoints

Pass complex json via hidden variable and read in mvc 3 controller

I want to do the following.
Pass a complex json object in a hidden input variable
Get that hidden variable through the form collection object.
Convert that hidden text value to a dynamic object which I can loop through to
get the data from it
So I think the first two items above I can do.
$("#hiddenVariableID").val(JSON.stringify(data));
Have a parameter called FormCollection collection in the MVC controller.
Then get the value the following way String data =
collection.Get("hiddenVariableID");
?? Not sure how to do this.
The data I'm passing is an array of objects. The objects are never the same so that is why I need to convert the results in some type of dynamic object that I can loop through.
I can't do an ajax call to do this because I want to stream down the data passed in the hidden variable. So it has to be through a form submission.
Thank you,
-Tesh
You can at that point use some JSON parser to convert between the string and a JSON object you can access dynamically. There are many JSON parsers out there, the code below shows how it can be done with two of them: the JavaScriptSerializer (part of the .NET Framework), and the JSON.NET (a non-MS library, but which IMO is really good).
public static void Test()
{
string JSON = #"[
{'name':'Scooby Doo', 'age':10},
{'name':'Shaggy', 'age':18},
{'name':'Daphne', 'age':19},
{'name':'Fred', 'age':19},
{'name':'Velma', 'age':20}
]".Replace('\'', '\"');
Console.WriteLine("Using JavaScriptSerializer");
JavaScriptSerializer jss = new JavaScriptSerializer();
object[] o = jss.DeserializeObject(JSON) as object[];
foreach (Dictionary<string, object> person in o)
{
Console.WriteLine("{0} - {1}", person["name"], person["age"]);
}
Console.WriteLine();
Console.WriteLine("Using JSON.NET (Newtonsoft.Json) parser");
JArray ja = JArray.Parse(JSON);
foreach (var person in ja)
{
Console.WriteLine("{0} - {1}", person["name"].ToObject<string>(), person["age"].ToObject<int>());
}
}

javascript to C# code Array implementation

this is javascript code, I want to change it into C# code, same as this is, b/c again I'll change it to javascript object
data: [['2-2010',45.0],['IE', 26.8],[ 'Chrome',12.8],['Safari',8.5],['Opera',6.2],['Others', 0.7]]
actually I'm writing a wrapper which will take values in C# language and then through json serialize I'll convert the code into json.
I can't do it like this, b/c at the time of creating json it would be some thing like
C#
class dataArray
{
public string browserId;
public double percentRate;
}
JS Generated by the above class but not useable for me b/c of the variable browser and percentRate
dataArray = {browser: 'chrome', 'percentRate':30.3}
I was expecting something like this List<string,double> but it would never work :D
You need a List of object arrays to get the output that you're looking for. I used JSON.net for the example code below.
class Program
{
static void Main(string[] args)
{
List<object[]> kvp = new List<object[]>()
{
new object[] {"2-2010", 45},
new object[] {"IE", 26.8},
new object[] {"Chrome", 12.8},
new object[] {"Safari", 8.5}
};
var json = JsonConvert.SerializeObject(kvp);
Console.WriteLine(json);
//deserialize it to a List<object[]>
var json2 = "[[\"2-2010\",45.0],[\"IE\", 26.8],[\"Chrome\",12.8],[\"Safari\",8.5]]";
var kvp2 = JsonConvert.DeserializeObject<List<object[]>>(json2);
}
}
No, you'd better have an array of dictionaries, each dictionary will be equal to the object and its key and values will be his property and value
You could use anonymous types which looks a lot like the JS code, but without single quoutes around percentRate. You could also use Tuples, which is Tuple<string, float> and is basically a pair of values. Multidimensional or jagged arrays are another option.

Convert string to variable name

I have an XML file, I have a node and I read all ChildNodes. The name of the childNode match to a variable I have to set with the value of this childNode.
In the loop, I'd like set :
myvar1 to MyValue1
myvar2 to MyValue2
The C# Code :
protected string myvar1;
protected string myvar2;
The XML content look like this :
<parameters>
<myvar1>MyValue1</myvar1>
<myvar2>MyValue2</myvar2>
</parameters>
C# set variables :
foreach (var item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
{
??????
}
Any idea ?
Thanks,
UPDATE 1:
the value "field" in the loop is null all the time.
public class ParametersTest
{
public string myvar1 { get; set; }
public string myvar2 {get; set;}
}
var type = typeof(ParametersTest);
foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
{
var field = type.GetField(item.LocalName);
field.SetValue(field, item.InnerText);
}
You can do it using Reflection:
var type = typeof(SomeClass);
var field = type.GetField(item.Name);
field.SetValue(null, item.InnerText);
RE: UPDATE 1
var parameters = new ParametersTest();
var type = parameters.GetType();
var s = #"<parameters>
<MyVar1>MyValue1</MyVar1>
<MyVar2>MyValue2</MyVar2>
</parameters>";
var xmlParamInstallation = new XmlDocument();
xmlParamInstallation.LoadXml(s);
foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
{
var field = type.GetProperty(item.LocalName);
field.SetValue(parameters, item.InnerText, null);
}
If you are seeking to assign variables based on the names of nodes in XML, you have at least a couple options:
Deserialize the XML structure into an object with corresponding member names
Populate the variables using reflection
Populate the variables using dynamic method calls/expression trees that know how to read the contents of the XML node into an object property.
All of these approaches suggest a more object-oriented approach to the problem then just populating a few variables, but it would be easy to create a lightweight structure with the appropriate members which is populated by reading the XML document.
You could also use a key-based collection (like a Dictionary<string, string>) to store the values if you are just looking to build a simple name/value collection from the source XML.
If you put the names and values in a dictionary, you can easily get the values by name:
Dictionary<string, string> parameters =
xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes
.ToDictionary(n => n.Name, n => n.InnerText);
myvar1 = parameters["myvar1"];
myvar2 = parameters["myvar2"];
You could either do as "Default" said, or you could look into Reflection. By using the Type.GetMember(string) method you could find a member with the given name (the tag name in your XML) and set its value.
EDIT
Samich beat me, so I'll give him +1 - he's got sample code as well.
You can check out the XmlSerializer class

Categories

Resources