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.
Related
[{
"$type": "foo",
"key" : "value"
}]
I don't serialise this message, its done as part of a framework.
The array is unnecessary, I'm just interested in first type and values etc, this is invariable.
I CAN do it using the following code, but it just feels a bit nasty! I know I am being particularly stupid, I started going down the road of creating a SerializationBinder but then thought I would like to get on with my life. It can't be that hard!
var json = reader.ReadToEnd().TrimStart('[').TrimEnd(']');
var foo = JsonConvert.DeserializeObject<Foo>(json , new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
As based on the comments the JSON string in the example is a valid JSON Array. Therefore the best solution would be to parse the JSON as an Array and then capture the first element. A basic example would be.
var foo = JsonConvert.DeserializeObject<Foo[]>(json)[0]
For a safer way to handle this would be to first get the array and then check if the result is valid such as.
Foo foo = fooArray.Length > 0 ? fooArray[0] : null;
And for a more generic solution can be done as a generic method.
static T DeserializeObjectFromArray<T>(string json)
where T: class
{
var arr = JsonConvert.DeserializeObject<T[]>(json);
return arr != null && arr.Length > 0 ? arr[0] : null;
}
Where in this method you can simply call
Foo foo = DeserializeObjectFromArray<Foo>(json);
This does the same as the second solution but can be reused for generic classes.
Cheers.
You can deserialize this to a list of dictionary like below
List<Dictionary<string, string>> values = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(a);
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>());
}
}
Can I define an array such that the first element is String, the Second is an int and the third is a textbox?
It's like when we create a List we choose type of element List<string >
Update from Comment:
Sorry I couldnt explain.I need to like
this List<string,int,object> Firstly i
will set type and when i call the list
i will not need to cast
thanks
create list of objects. in C# everything is derived from object
List<object> list = new List<object> {"first", 10, new TextBox()};
EDIT(To comment):
Then you should create seperate class to hold those three items , or use Tuple
List<Tuple<string,int,TextBox>> list;
You can declare an array of object and do that. You're talking about a mixed type array, right?
var arr = new object[] { "Hi", 42, 3.7, 'A' }
If you need an array that has elements without a common base-class other than object, then you're going to need an array of objects!
object[] myArray = new object[] { "Hi", 23, new TextBox() };
Note that this is not really something you should doing. If you need to associate disparate types like this, a class makes much more sense.
You want a Tuple<string,int,TextBox>, not an array.
IMHO the best way to do this is through a List<> of objects:
String s = "hey!";
int i = 156;
TextBox t = new TextBox();
List<object> list = new List<object>(3);
list.Add(s);
list.Add(i);
list.Add(t);
The reason this works is because (almost?) everything in C# derives from the base-class object
Arrays are typically homogeneous collections, which means that every object contains in the array is of the same type (or at least shares a common parent type). An array of [string, int, textbox] could be defined as an object[] but that's really misuse of arrays.
Just create a proper class which contains the 3 fields.
class MyType {
public string myString;
public int myInt;
public Listbox myListbox;
}
If you're looking make a list of string, int, textbox, you can either create a class which has those members or look at the Tuple class in .net 4.0
List<Tuple<string,int,TextBox>
Define a class that contains the 3 types then define an array that contains the new type.
Object[] myObjects = new Object(){"myString", 42, textbox1};
System.Collections.Generic.Dictionary<string, object> source = new System.Collections.Generic.Dictionary<string, object>();
source.Add("A", "Hi");
source.Add("B", 10);
source.Add("C", new TextBox());
While accessing
string str = Convert.ToString(source["A"]);
int id = Convert.ToInt16(source["B"]);
TextBox t = (TextBox)source["C"];
I will suggest that you create a Type such as
enum ItemType { Int, String, Textbox }
class MyType {
public object objValue;
public ItemType itemType;
}
List<MyType> list = new List<MyType>();
.......
You can iterate through the list or extract the list by type such as below.
var intList = list.Where(e=>e.itemType == ItemType.Int);
Of course you can achieve the above with the enum and using the reflected Type info directly from the object, but I just think it is clearer this way also more explicitly list out the type your list can hold rather than just all type in the CLR
I'm looking for something similar to List<T>, that would allow me to have multiple T. For example: List<TabItem, DataGrid, int, string, ...> = new List<TabItem, DataGrid, int, string, ...>().
If you are using .NET 4, you could have a List<Tuple<T1, T2, ...>>
Otherwise, your choice is to implement your own type.
Create a class that defines your data structure, and then do
var list = new List<MyClass>();
Normally you'd just have List<MyClass> where MyClass had all those other ones as members.
If it can have any old type, then you need to use an ArrayList.
If you know ahead of time what you'll have in there, then you should either create your own structure, or use a Tuple.
Looks like you're after List<object>?
Tuples are best if you are using .net 4.0. But if you are working 3.5 or below, multidimensional object array is good. Here is the code. I have added 3 different types in a object array and I pushed the same to list. May not be the best solution for your question, can be achieved with object array and list. Take a look at the code.
class Program
{
static void Main(string[] args)
{
object[,] OneObject = new object[1,3]{ {"C Sharp",4,3.5 }};
List<object> MyList = new List<object>();
MyList.Add(OneObject);
object[,] addObject = new object[1,3]{{"Java",1,1.1}};
MyList.Add(addObject);
foreach(object SingleObject in MyList)
{
object[,] MyObject = (object[,])SingleObject;
Console.WriteLine("{0},{1},{2}", MyObject[0, 0], MyObject[0, 1], MyObject[0, 2]);
}
Console.Read();
}
}
Instead of trying in C# 4, you can give the old version features a chance here.
It seems you don't need a strongly typed collection here, in that case ArrayList is the best option.
I've read lots of tutorials on how to deserialize a JSON object to an object of a particular using DataContractJsonSerializer. However, I'd like to deserialize my object to a Dictionary consisting of either Strings, Arrays or Dictionaries, such as System.Json does with SilverLight when I say JsonObject.Parse(myJSONstring).
Is there an equivalent to System.Json that I can use in my WPF project?
(just a short background: I'm fetching JSON objects that have way to much info, and I just want to use a little bit to fill out a String array)
Cheers
Nik
Just use .NET's built-in JavaScriptSerializer.
var jss = new JavaScriptSerializer();
var data = jss.Deserialize<dynamic>(jsonString);
//"data" actually implements IDictionary<string, object>
var p1 = data["Property1"];
var p2 = data["Property2"];
Don't forget to reference "System.Web.Extensions"
Take a look at the C# section (scoll to the bottom) of http://json.org/, they have several implementations of serializers and parsers that should help.
I successfully use JayRock: http://jayrock.berlios.de/
public class JayRockMarshaller : IMarshaller
{
public ICollection Read(string text)
{
return (ICollection)new ImportContext().Import(new JsonTextReader(new StringReader(text)));
}
public string Write(ICollection objectToMarshal)
{
var writer = new StringWriter();
new ExportContext().Export(objectToMarshal, new JsonTextWriter(writer));
return writer.ToString();
}
}
Works for both Dictionaries and Lists like a dream.
Also look at https://github.com/jlarsson/Kiwi.Json it handles all sorts of datatypes and you can easily create your own converter if the built in doesn't fit.
There's blog where you can find samples on this for example: http://dancewithcode.wordpress.com/2012/03/24/case-study-custom-json-converter-for-datatable/