Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse C# object list into key value pair in JS

I have a JSON object constituting of column model attributes of a grid. I want to populate a dropdown in the grid, for that I have a object list with ID - Value pair.

The grid model takes the values in the following format:

values: { "be": "Belgium", "fr": "France", "uk": "Great-Britain", "nl": "Nederland" }

My anonymous object structure is the following:

List<Object> valueList = new List<Object>();
var item1 = new { ID = "M", Value = "Male" };
var item2 = new { ID = "F", Value = "Female" };
valueList.Add(item1);
valueList.Add(item2);

The array structure after $.parseJSON is:

    [
Object
ID: "M"
Value: "Male"
__proto__: Object
, 
Object
ID: "F"
Value: "Female"
__proto__: Object
]

EDIT:

Using this for json converter:

var jsonSerialiser = new JavaScriptSerializer();
json = jsonSerialiser.Serialize(model);
return json;

Where model is a list with other grid attributes and List of values.

How would I construct a JSON formatted data from this, such that I have similar results? Is there an proper way to it? Or would I have to do something similar to splitting and making a string out of it?

like image 268
faizanjehangir Avatar asked Dec 02 '25 02:12

faizanjehangir


1 Answers

You can use a dictionary:

Dictionary<string, string> valueList = new Dictionary<string, string>();
valueList.Add("M", "Male");
valueList.Add("F", "Female");

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(new { values: valueList });
return json;

This will serialize as:

{"values":{"M":"Male","F":"Female"}}
like image 190
Richard Dalton Avatar answered Dec 04 '25 16:12

Richard Dalton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!