converting C# Lists (more than one) to JavaScript Associative Arrays -
i after this:
i have multiple lists in c# so:
list<string> names = new list<string>() { "name1", "name2", "name3" }; list<double> values = new list<double>() { 1, 2, 3 };
i want serialize them array in javascript (i looking return string) this:
[ { name: "name1", value: 1 }, { name: "name2", value: 2 }, { name: "name3", value: 3 } ]
so far have tried this:
public class bmdata { string _name; public string name { { return this._name; } set { this._name = value; } } double _value; public double value { { return this._value; } set { this._value = value; } } }
zip them , wrap "data item" class. want keep functionality other reason. zipped key value pairs new class:
list<bmdata> namesvalues = names.zip(values, (x, y) => new bmdata{name = x, value = y}).tolist();
finally tried serialize so:
var serializer = new javascriptserializer(); string jsdata = serializer.serialize(namesvalues);
but return this:
[ {"name":"name1","value":1}, {"name":"name2","value":2}, {"name":"name3","value":3} ]
it's "" around name , value killing key:value association. ideas?
thank you!
you can achieve need using json.net serializer. check out next code , change according needs:
list<bmdata> namesvalues = new list<bmdata> { new bmdata { name = "name1", value= 1 }, new bmdata { name = "name2", value= 2 }, new bmdata { name = "name3", value= 3 } }; string jsdata = "[]"; var serializer = new jsonserializer(); using (var stringwriter = new stringwriter()) { using (var writer = new jsontextwriter(stringwriter)) { writer.quotename = false; serializer.serialize(writer, namesvalues); } jsdata = stringwriter.tostring(); }
however, have remark produce invalid json, it's need.
result:
[ {name:"name1",value:1.0}, {name:"name2",value:2.0}, {name:"name3",value:3.0} ]
Comments
Post a Comment