problem in getting Value from Json Key Value Pair
I am following this link to build a Client side repeater.
According to the above link to retrive the value from a Json key-value pair we can use result[i].property,for example
for (var post in msg)
{
var x= msg[post].Date;
alert(x);
}
Here x
returns the date from Json string. When I am trying to use the same with my data, it always returns as undefined
. I tried to pop up an alert(msg.d)
that shows a nice Json string with all my data. But when I try msg[post].Date(property name)
it's always returning undefined
.
Please help..
Thanks in advance.
Update:
From the backend I am returning a generic list and then converting it into Json using the following code.
public static string ConvertToJSON(this object obj) {
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new Memo开发者_如何学运维ryStream();
serializer.WriteObject(ms, obj);
string jsonobj = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return jsonobj;
}
then I am appending the returned Json to a stringbuilder and returning it to the Jquery ajax method.The returned Json looks like a string , not an object and hence I am unable to get any value from Json key value pair..
Update:
It sounds like you're doubly serializing the data on the server-side, returning a JSON string that gets serialized as JSON itself. When that reaches the client-side and jQuery deserializes the first layer of JSON automatically, you're still left with the JSON string you manually built.
You should return the List<T>
as the return value of your service method and let the framework handle JSON serialization.
Original Answer:
Assuming the object is still contained in ASP.NET AJAX's ".d" wrapper, as you implied:
for (var post in msg.d) {
var x = msg.d[post].Date;
alert(x);
}
Or, a traditional loop, which might be more straightforward:
for (var i = 0; i < msg.d.length; i++) {
var x = msg.d[i].Date;
alert(x);
}
What about the message, if you add this to your ajax does that help?
dataFilter: function(data) {
var msg;
if (typeof(JSON) !== 'undefined' &&
typeof(JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
Note that you then process this as msg, not msg.d like so:
success: function(msg) {
SaveSuccess(msg);
},
Looks to me like you got an array of objects to begin with, using your sample the following works:
messages = [{"AnsNo":0,"Answer":"","Category":"Help Centre.Mortgages.Existing customers","ClickURL":null,"ID":7,"Question":"How do I re-mortgage to you?","RecNo":0,"ValidFrom":"\/Date(-62135596800000+0000)\/","ValidUntill":"\/Date(-62135596800000+0000)\/"}]
for(i in messages)
{
message = messages[i];
//Says "Help Centre.Mortgages.Existing customers"
alert(message.Category)
//To get all key/value pairs
for(key in message)
{
//Alerts all key value pairs one by one
alert("Key:" + key + ", Value:" + message[key]);
}
}
精彩评论