In my asp.net web page, I have prepared the JSon string with the help of JavaScriptSerializer class.
And i have spit the Json string in to the HTML markup with the help of RegisterStartupScript method and it looks like this,
C#.net code to prepare the json string,
System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, string>> glAccts = new List<Dictionary<string, string>>();
Dictionary<string, string> row;
foreach (DataRow dr in _dtProfitCenterRawData.Rows)
{
row = new Dictionary<string, string>();
row.Add(dr[0].ToString(), dr[1].ToString());
glAccts.Add(row);
}
string jsonObj = jsSerializer.Serialize(glAccts);
string script = "var glList = " + jsonObj + ";";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSONObj", script, true);
The glList variable on the client html looks like this,
var glList = [
{ "1110005": "1110005 - X1" },
{ "1110008": "1110008 - X2" },
{ "1110011": "1110011 - X3" },
{ "1110020": "1110020 - X4" }
];
I want to bind this json string to dropdownlist control. Please suggest how to perform that? I tried to perform the following action to view the data inside the object, but it does not give me the real values. It gives [object] in the alert methods.
Please suggest the fix to the problem..
$.each(glList, function (val, text) {
//$('#mySelect').append(new Option(text, val));
alert(text); alert(val);
});
Try this here. If you itereate through glList you get the objects but not their properties.
function jsonTest() {
$.each(glList, function(index, obj) {
($.each(obj, function (key, value) {
$('#mySelect').append(new Option(key, value));
}));
});
}
Use JSON.Net instead JavaScriptSerializer to serialize a Dictionnary.
Or you can try to cast to object before serialize
jsSerializer.Serialize((object)glAccts)
try
var glList = [
{ 1110005: "1110005 - X1" },
{ 1110008: "1110008 - X2" },
{ 1110011: "1110011 - X3" },
{ 1110020: "1110020 - X4" }
];
Related
I have json file like this:
{
"fields": {
"customfield_10008": {
"value": "c1"
},
"customfield_10009": {
"value": "c2"
}
...
}
}
and I would like to create dictionary in c# like:
key: value
"customfield_10008":"c1"
"customfield_10009":"c2"
How I can achive this? I load json in this way,
dynamic json = JsonConvert.DeserializeObject(File.ReadAllText("data.json");
and don't know how to create dict like above
A little bit linq tricks can help you
var dict = JObject.Parse(File.ReadAllText("data.json"))["fields"]
.Cast<JProperty>()
.ToDictionary(x => x.Name, x => (string)x.Value["value"]);
Come through the values and collect them:
var result = new Dictionary<string, string>();
foreach (var field in obj.fields)
{
result.Add(field.Name, Convert.ToString(field.Value.value));
}
If you have json which do not have type in compile time, you can use dynamic type at that time.
I would parse above json using dynamic type and generate dictionary with parsed value :
var dicValues = new Dictionary<string,string>(); // this dictionary contains key value pair result
dynamic res = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("data.json");
dynamic availableFields = res["fields"];
if (availableFields != null)
{
foreach (var field in availableFields)
dicValues.Add(field.Name, field.Value["value"].Value);
}
I am working on MVC 5 project.
string hdPrimUserFirstReg = "{\"ProjectName\":\"wwwwwww\",\"ClientName\":\"asdw\",\"ProjectType\":\"2\",\"ProjectLocation\":\"asdfasdfs\",\"Status\":\"Completed\"},\"Form6\":null}","hdPremUserProject":"","hdclientLogo":"","hdProjectTitle":"","ProjectName":"eeeeeee","ClientName":"asdwedfswe","ProjectType":"1","ProjectLocation":"dfwea","Status":"Completed}";
I want to create a list of ProjectName from the variable hdPrimUserFirstReg JSON format data and also from the Form 5 into the public IList<string> listProjectName { get; set; }
And this is my java-script,
AddProjectList: function (e) {
debugger;
if (this.validateForm()) {
debugger;
var hidvalue = $('#hdPrimUserFirstReg').val();//// hidden field from same form
var hidJson = JSON.parse(hidvalue);
var json = {};
$.each($('#frmSubmitPremUserRegFirst').serializeArray(), function (i, field) {
json[field.name] = field.value || '';
});
hidJson.Form5 = json;
var str = JSON.stringify(hidJson);
$('#hdPrimUserFirstReg').val(str); // hidden field from same form
}
},
Error: cannot deserialize the current json object (e.g. {“name”:“value”}) into type 'system.collections.generic.list`1
How can I do this ?
Please help me...
var hdPrimUserFirstRegList =
JsonConvert
.DeserializeObject<List<hdPrimUserFirstRegModel>>(pageVM.hdPrimUserFirstReg );
var projectsNames = hdPrimUserFirstRegList.Select(x=>x.ProjectName).toList();
And create model hdPrimUserFirstRegModelcontains all json object properties.
Try this
var listProjectName = JsonConvert .DeserializeObject<List<hdPrimUserFirstRegModel>>(pageVM.hdPrimUserFirstReg ).Select(x => x.ProjectName).ToList()
I need to read data from a Json string in C#.
The Json string is like:
{
"data_level":{
"performance":{
"#value":"1000",
"#size":"10",
},
"points":{
"#type":"profit",
"tier":{
"#below":"80",
"#above":"100"
},
"kids":[
{
"#kid":"150"
},
{
"#kid":"200"
}
]
}
}
My C# code:
var my_dic = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json_string);
var my_data = my_dic["data_level"]
string v = my_data["performance"]["#size"];
For "kids", I have two child "kid" have the same name but differne value. How to get all of them instead of only the one last read ?
Any help would be appreciated.
You should leave out the last [0] .
For the updated question:
my_children = my_dic["points"]["kids"];
foreach (KeyValuePair<string, int> pair in my_children)
{
Console.WriteLine(pair.Key, pair.Value["#kid"]);
}
This should work...
I'm scraping some code together from samples on the web that takes a single row of data (returned row from SP) and uses JSON object serializer to send it back to the client aspx javascript page. To give you an idea of how the data is being built...
public static string GetLogEntry(DataTable table, string id)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in table.Select("UID =" + id))
// foreach (DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
var json = jss.Serialize(rows);
return json;
I understand I have an unnecessary loop here because this particular SP is only designed to return a single row. I'll be working on that in the next chapter. My real issue is I don't understand how to extract the data I need.
My client loop is returning the data but I'm having a hard time referencing specific column data individually.
success: function (json) { //ajax call success function
var obj = jQuery.parseJSON(json); // this line isn't really doing anything right now
eval("var datax = " + json);
for (var propertyName in $(datax)[0]) {
alert('data: ' + propertyName ); } //this returns only the column names
$(data).each(function (key, val) {
for (var propertyName in val) {
alert('data: ' + val[propertyName]); }
So what I'm wanting to do is access an element by the column name like I've seen in other examples....
alert(json.columnName) //returns undefine.
Thanks in advance for your time.
Depending on how your ajax call is made, the variable json in your success handler is already a javascript object literal.
function successHandler(resp){
var data = resp;
$.each(data, function (index, row){
var key;
foreach (key in row){
if (row.hasOwnProperty(key)){
console.log(key, row[key]);
}
}
});
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "some url",
data: "{}",
dataType: "json"
}).done(successHandler);
It would help a lot if you could post the data as returned by the server. That would give us an idea of the structure of json.
As such, there shouldn't be any need to use eval or to parse the server response.
Btw, there is no such thing as a JSON object. JSON is simply a format to serialize and pass around javascript object literals. The following,
var data = new List<Dictionary<string, object>>
{
new Dictionary<string, object>
{
{ "Col1", 1.0}, { "Col2", 2.0}
},
new Dictionary<string, object>
{
{ "Col1", 1.1}, { "Col2", 2.2}
},
};
will be converted to the following string as per the JSON format:
"[{\"Col1\":1,\"Col2\":2},{\"Col1\":1.1,\"Col2\":2.2}]"
jQuery ajax will automatically parse this string and pass the resultant array to the success handler. For this to happen, jquery needs to be told to expect json data and the server needs to send back a string with the mimetype application/json; charset=utf-8
Many thanks in advance for your help.
I have the following code in an action which returns a json serialized string of List<Dictionary<string,int>>, but I am struggling to get the data into a usable format in the view, using JQuery. I want to be able to iterate through each dictionary.
I have done this before using a List, which worked, so I could I suppose create a new model but I am sure I should be able to deserialize this.
I would greatly appreciate it if someone could suggest a way to deserialize this data or a better way to send the data in the first place.
MenuController:
public JsonResult Populate(string id) {
// Get and process data, creating all, a List<Dictionary<string,int>>
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize((object)all);
return Json(json, JsonRequestBehavior.AllowGet);
}
I also tried the following instead of using the JavascriptSerielizer, but it had the same result:
return Json(JsonConvert.SerializeObject(all), JsonRequestBehavior.AllowGet);
cshtml jquery:
<script type="text/javascript">
$.get('#Url.Action("Populate","Menu")', { id: "MO" }, function (data) {
console.log(data);
var obj = jQuery.parseJSON(data);
console.log('obj: ' + obj);
for (var o in obj) {
console.log('o is: ' + o);
}
})
.done(function (d) {
console.log('done: ' + d);
})
.fail(function (d) {
console.log('fail: ' + d);
});
</script>
In the console I get:
data
[{"foo":2,"bar":0,"ray":3,"doh":1},{"mee":1,"so":0,"lah":2,"far":0}]
obj
obj: [object Object],[object Object]
o
o is: 0
o is: 1
done
done: [{"foo":2,"bar":0,"ray":3,"doh":1},{"mee":1,"so":0,"lah":2,"far":0}]
Many thanks for your help.
So lists get translated to arrays and dictionaries to objects, so it seems that everything is working fine. In Javascript, you have been handed an array with two objects in it. You could iterate each object (which is the translated dictionary) as follows:
var data;// your downloaded JSON object
for(var i = 0;i < data.length; ++i) //for enumerating array
{
var obj = data[i];
for(var propName in obj) //for enumerating the properties of an object
{
var value = obj[propName];
alert("item : " + i + " : prop : " + propName + " : value : " + value);
}
}