johnny 5
johnny 5

Reputation: 20997

String does not act as valid json object when returned from Controller

I'm trying to read a string from a json response however I get an error:

SyntaxError: Unexpected token c in JSON at position

I have a controller which returns a guid as a string from the DB

[HttpPost("TransactionOrderId/{id}")]
public async Task<string> TransactionOrderId(int id)
{
    return await this._service.GetTransactionOrderId(id);
}

In my Angular 2 application I'm subscribing to my provider which has trouble parsing my response from my server.

this.meetingsProvider.getTransactionOrderId(this.meetingId).subscribe((transactionId: string) => {
    this.transactionOrderId = transactionId;
});

And My Provider code looks like so:

getTransactionOrderId(meetingId: number): Observable<string> {

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return  this.http.post(`${this.apiUrl}/${this.route}/transactionOrderId/${meetingId}`, null, {
        headers: headers
    }).map(res => <string>res.json());
}

My Server Responds with the proper transaction order id the response looks like so:

status: 200
statusText: "OK"
type: 2
url: "http://localhost/api/meetings/transactionOrderId/4"
_body: "0c290d50-8d72-4128-87dd-eca8b58db3fe"

I have other api calls using the same code that return bool which return fine, but when I try to return string I get a parsing error why?

Upvotes: 0

Views: 743

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

That's not a valid JSON object, that's why you get that error. A JSON object starts with { and ends with }.

If you want to be able to JSON-deserialize that, use:

public async Task<JsonResult> TransactionOrderId(int id)
{
    return Json(await this._service.GetTransactionOrderId(id));
}

Note that if you return anything that is not a string, ASP.NET Core should JSON-serialize it (that's the default serializer anyway).

Upvotes: 3

Related Questions