0

I have this user class

public class User
{
    public string name { get; set; }
    public string phone { get; set; }
    public string address { get; set; }
}

var users = new List<User>(){
    new User(){
        name = "Chriss",
        phone = "45096820",
        address = "xxx, street."
    },
    ...
};

How do i return using ASP MVC Json method

return Json(users, JsonRequestBehavior.AllowGet);

that the return json format looks like the below

"Users"  :
    {
    "Chris" :
        {
            "phone" : "45096820",
            "address" : "xxx, street."
        },
    "Jason" :
        {
            "phone" : "406980968",
            "address" : "xxx, street"
        }
    }   
2
  • What happens if you have 2 users with the same name? Commented Feb 14, 2014 at 9:57
  • 1
    Note that what you've show is not valid JSON... Commented Feb 14, 2014 at 9:58

2 Answers 2

4

Generally, the "trick" to naming the outermost JSON variable (the root property, so to speak) is to create an anonymous object with exactly that property:

return Json(new { Users = users }, JsonRequestBehavior.AllowGet);

Will return an object with one array property (Users).

If you need a JSON object with one object property (Users) which itself has two properties (Chris and Jason), consider using a Dictionary<string, User> (the key being a user's name) instead of a List<User>:

var users = new Dictionary<string, User>
{
    { "Chris", new User { phone = "45096820", address = "xxx, street." } },
    { "Jason", new User { phone = "406980968", address = "xxx, street." } }
};

Json.NET will serialize dictionaries like your desired output JSON format.

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

2 Comments

notice the name? the name title is not in the result.
@JeeShenLee Now you were faster typing your comment than me updating my answer. ;)
1

In order to get exactly the same Json structure as you wanted, you will have to modify your User class to look like:

public class User
{
    public string phone { get; set; }
    public string address { get; set; }
}

(without the name, the name will be the Key in your dictionary)

and use a Dictionary:

Dictionary<string, User> dictionary = new Dictionary<string, Controllers.User>();
        dictionary.Add("Chris", new User() { phone = "45096820", address = "xxx, street" });
        dictionary.Add("Jason", new User() { phone = "406980968", address = "xxx, street" });
        return Json(new { Users = dictionary }, JsonRequestBehavior.AllowGet);

Comments

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.