0

Let's say we have this C# method:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetEventsJson()
{
  Event[] events = new Event[] {
  new Event
  {
    Ref = 1,
    Name = "Some Name",
    Date = new DateTime(2017, 3, 20, 12, 0, 0),
    Description = "Some Description",
    Localization = "Localization"
  }
  };
  return Newtonsoft.Json.JsonConvert.SerializeObject(events);
}

And we call this web service method via CORS request. It returns string like that:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"Ref":1,"Name":"Some Name","Date":"2017-03-20T12:00:00","Description":"Some Description","Localization":"Localization"}]</string>

Now, i'm trying to deserialize this back in JavaScript, I was trying to simple:

var data = jQuery.parseJSON(JSON.stringify(json));

or

var data = jQuery.parseJSON(json);

But it only returns error with second method:

Uncaught SyntaxError: Unexpected token < in JSON at position 0

Or does nothing with first method (I cant get for example data.Description because it says it's undefined)

So the question is: what is proper way to deserialize JSON returned by C# webservice?

Roddeck
  • 45
  • 7
  • 2
    The problem is your service returns xml. From what I understand, this is an .asmx. Make sure to have the attribute [System.Web.Script.Services.ScriptService] on your class – Phil-R Mar 29 '17 at 20:20
  • can you use jQuery? If yes, you can write: var xmlDoc = $.parseXML( xml ); var jsonString = $(xmlDoc).find('string').text(); var jsonObj = JSON.parse(jsonString); – gaetanoM Mar 29 '17 at 20:22

0 Answers0