Reputation: 34407
I have an List error Entity which I used to pass errorId and error message to the UI layer.
public class ErrorEntity
{
public int ErrorId
{
get;
set;
}
public string ErrorMessage
{
get;
set;
}
}
}
I send the object to the Javascript I am serializing it to JSON.
The Json I am getting after serialization look like
[{"ErrorId":1,"ErrorMessage":"Test has not been prepared for tag EP105"},{"ErrorId":2,"ErrorMessage":"Test has not been prepared for tag EP105"}]
Now I need to parse this Json string to show the error message to the user. Please let me know how can I parse it. Do I need to write a for loop to traverse with in it.
EDIT In my master page I am trying to parse it.
function ShowErrorMsg(jsonObject) {
for (i = 0; i < jsonObject.Object.length; i++) { //Object is undefined here.
alert(jsonObject.Object.ErrorMessage);
}
}
Upvotes: 0
Views: 340
Reputation: 1070
There is support in most browsers for parsing json, I recommend to use jQuery for this - you also can take a look at this
Be aware - Its better to use a library - and not using JS for this (JS is from the devil ;) )
Upvotes: 0
Reputation: 262979
Prefer JSON.parse() if it's available:
var jsonArray = JSON.parse(serializedString);
window.alert(jsonArray[0].ErrorMessage);
Fall back to eval() otherwise:
var jsonArray = eval(serializedString);
window.alert(jsonArray[0].ErrorMessage);
Upvotes: 2