2

I am making a web api call and I want the controller method to return data in json format.

The model class I used is User.cs :

public partial class User
{
     public int UserID { get; set; }
     public string city { get; set; }
     public string email { get; set; }
     public string firstName { get; set; }
     public string lastName { get; set; }
     public string phone { get; set; }
     public string password { get; set; }
 }

I want to return all the users email data in json format through the following controller method.

public string GetUsers()
{
   IEnumerable<User> users = db.Users.ToList();
   var jsonSerialiser = new JavaScriptSerializer();
   var json = jsonSerialiser.Serialize(users);
   return json;
   //string json = JsonConvert.SerializeObject(users);
   //return json;
}

All I am getting is empty json like:

[]

Please help. I have covered all the methods recommended on stackoverflow.

1 Answer 1

3

This is a lot simpler than you think, you do not need to use a jsonSerializer.

You can change your method to the following:

public List<string> GetEmails()
{
    return db.Users.Select(e => e.email).ToList();
}

Then if the client specifies application/json the content is returned as json.

Please note with the above, I am only sending back the email address and not the full user details as I very much doubt you will want to send passwords out as json.

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

6 Comments

your code wont work. you create an object with an email property but try to return it as a string. Either just .Select() the email or change the return type to List<object>
@jgauffin Good point, I originally had it like above but changed it. Updated now, thanks.
you still returned an object. corrected it for you ;) Either way a +1 for the explanation why it works (and how).
@jgauffin Thanks again, that will teach me for trying to answer without testing first. Too worried someone beats me to the answer. :)
what if I want to call my api like api/user to show me the firstName and email of all users in json format.
|

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.