0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That did it, thank you. I was asked to produce kind of "Uniform Response" from all my methods in the service, and I thought of something like this. Can you suggest me how I could involve the http status code checking in my case ?
I can't see what you're trying to do, but you can consider returning an HTTP error (like 409 Conflict if applicable).
I am building a restful wcf service, that I will later consume from android client.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.