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

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>());
}
}

Related

DataContractJsonSerializer dynamic object deserialization

I would like to go with DataContractJsonSerializer instead of any third party libs like Json.NET I need to deserialize Json stream which can be one of my C# classes, and I dont know which one it is what i want to do is Deserialize json data -> determine type of this object -> do something with deserialized object according to type of this object. Is there anything to do with DataContractJsonSerializer.KnownTypes Property? Im really new to json.
what i want to do is Deserialize json data -> determine type of this object -> do something with deserialized object according to type of this object. Is there anything to do with DataContractJsonSerializer.KnownTypes Property?
Yes, it is related to the known types. Firstly, you need to specify the type you want to de-serialize in the constructor function. Then you can specify the types may be present in may be present in the object graph.
DataContractJsonSerializer Constructor (Type, IEnumerable)
But I still recommend you using the JSON.NET which will be easier than DataContractJsonSerializer, and the performance is even better. In ASP.NET Web API, JSON.NET is the default JSON serializer.
or JavaScriptSerializer
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(strRet);
StringBuilder sbErr = new StringBuilder(string.Format("{0} ({1}): {2}", rep.StatusDescription, dict["code"], Environment.NewLine));
if ((dict["errors"] is Dictionary<string, dynamic>)) {
foreach (KeyValuePair<string, dynamic> item in dict["errors"]) {
sbErr.AppendFormat("{0}=", item.Key);
foreach (string item2 in item.Value)
sbErr.AppendFormat("{0}. ", item2);
}
}

C# How to read Object

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.

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

How do you parse a JSON.NET file without a defined structure?

I'm using an API from OpenCalais that gives me a json string that contains a bunch of JSON objects. The problem is that depending on what I pass into the API the structure of the JSON string changes, which means that I can't cast the deseralization against a custom class I could make. Another problem is that the output isn't in key value form, but rather a complicated object structure. Here is an example of the output-
{"doc":
{"info":
{"allowDistribution":"true",
"allowSearch":"true",
"calaisRequestID":"c1cdd79a-ed89-8431-138c-50e8a37100f9",
"externalID":"17cabs901",
"id":"http://id.opencalais.com/0RCcU306*HTR05*7HlUb5A",
"docId":"http://d.opencalais.com/dochash-1/6188237f-a2a5-3263-95b7-ea894ba98298",
"document":"Bill Gates worked at Microsoft from 2008 to 2011. He is also married to Melinda Gates.",
"docTitle":"",
"docDate":"2012-07-26 15:51:00.885",
"externalMetadata":"",
"submitter":"ABC"}
So you can see there are multiples levels of objects here and there is no key value structure. What I need from this code is essentially all of the name/value info in a dictionary. Then I can sort through based on the keys to the relevant info. It would also be cool if I could somehow also grab the parent of the object value. So for example the output I want is key: allowSearch, value: true, parent: info. I have been trying to mess around with different method of deserialization, dynamic objects, and just plain parsing using functions like .Ancestor and I haven't found anything useful. Any help would be greatly appreciated.
Have you looked at JSON.NET? It can dynamically parse JSON which you can then iterate through:
using Newtonsoft.Json.Linq;
JObject rootObject = JObject.Parse(jsonString);
You can iterate through the children, or search for other nodes like this:
JToken info = rootObject.SelectToken("info");
Json.NET support LINQ to JSON under the Newtonsoft.Json.Linq namespace.
The example to use JObject
JObject o = JObject.Parse(#"{'CPU': 'Intel','Drives': ['DVD read/writer','500 gigabyte hard drive']}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
You can use DeserializeObject which essentially returns a Dictionary<string, object>.
For example:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> myGraph = (Dictionary<string, object>)serializer.DeserializeObject(myJson);
To read stuff from the myGraph dictionary, you will have to cast each step of the way.
For example:
Dictionary<string, object> doc = (Dictionary<string, object>)myGraph["doc"];
Dictionary<string, object> info = (Dictionary<string, object>)doc["info"];
string externalID = (string)info["externalID"];
I'm sure you could genericize it a bit, but I think that should work with the json you posted.

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.

Categories

Resources