开发者

How to parse JSON created by WCF DataContract object

开发者 https://www.devze.com 2023-03-06 15:51 出处:网络
I have an object decorated with [DataContract] attribute and my WCF service is returning this as JSON like this:

I have an object decorated with [DataContract] attribute and my WCF service is returning this as JSON like this:

{"GetCommentsByPostResult":[{"CommentCreated":"\/Date(1305736030505+0100)\/","CommentText":"Comment 1"},{"CommentCreated":"\/Date(1305736030505+0100)\/","CommentText":"Comment 2"},{"CommentCreated":"\/Date(1305736030505+0100)\/","CommentText":"Comment 2"}]});

Ive attempted to iterate through the CommentCreated with this jQuery code:

$(data).each(function () 
{
     alert(this.CommentCreated);
});

But all I get i开发者_StackOverflow社区s an alert box with 'undefined in' so I changed it to:

 $(data).each(function () {

         $(this.GetCommentsByPostResult).each(function () {

                      alert(this.GetCommentsByPostResult);
         });

 });

but that still doesnt work. What I want to do is iterate the CommentCreated and throw them to an alert box....


I'm not sure, but I don't think this would be the current element when calling each. Also, why are you wrapping the data variable with the jQuery function? jQuery collections are for DOM elements.

$.each(data.GetCommentsByPostResult, function (e) {
    alert(e.CommentCreated);
});


Depending on how you are acquiring the data (a library? custom code?) you will most likely have to convert the JSON string first into an actual JavaScript object. Many browsers have built in methods for doing this, though you may need to take advantage of a 3rd party library to take advantage of those that do not have out-of-box support. I would recommend JSON-js as it follows the same syntax as those found built into some browsers.

var obj = JSON.parse(data);

Once you have this object, you can now access the data with standard JavaScript dot or bracket notation:

var comments = obj.GetCommentsByPostResult; // or...
var comments = obj['GetCommentsByPostResult'];

Those two lines are equivalent. To iterate the comments, as you are trying to do, you could try:

$.each(obj.GetCommentsByPostResult, function (e) {
    alert(e.CommentCreated);
});

Also, I would recommend using console.log() instead of alert(), and a browser that supports inspection of the logged objects. This would be FireFox with the Firebug extension, or Chrome with their developer tools (Ctrl-Shift-J to activate). Not sure about the status of this type of tool in IE9, though I would not be surprised if there was an equivalent tool there as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消