Reputation: 9806
I have been trying a lot to return a json response from wcf restful service using ef entities as source, when I came to know that the it is not possible to do it with the integrated libraries. So after some 3rd party library googling I came to know about Json.net library, which is able to handle EF entities. So far so good, the library works and does its job perfectly. But then I faced the problem of re-serialization of the object serialized previously with Json.net library, because when I was returning it the visual studio integrated library was serializing again, so I kept getting some malformed json in output, containing some back slashes ( \ ). Then finally I found a method to return the serialized json string avoiding 2nd serialization, with the following method:
public Message GetProblems()
{
using (MojDBEntities context = new MojDBEntities())
{
//not a good solution, but ok, till I find a better one
context.ContextOptions.LazyLoadingEnabled = false;
var temp = context.Problems.ToList();
var serializedObject = JsonConvert.SerializeObject(temp);
return WebOperationContext.Current.CreateTextResponse (serializedObject,
"application/json; charset=utf-8",
Encoding.UTF8);
}
}
and it works. The problem is that I don't want to return just the actual json data, but as well another field called status, which will tell me whether the response is correctly completed( e.g. status = 0 means ok, so i can proceed to take the actual json data). How to accomplish this?
Upvotes: 0
Views: 54
Reputation: 151720
Something like this?
var response = new
{
status = 0,
data = temp
};
var serializedObject = JsonConvert.SerializeObject(response);
return WebOperationContext.Current.CreateTextResponse(serializedObject);
But you should rely on HTTP for the status code, not the response message itself.
Upvotes: 1