Mukil Deepthi Mukil Deepthi - 5 months ago 10
JSON Question

Webapi how to have a name the json response instead starting with JSON

I have developed an asp.net webapi and testing it using fiddler. I am getting a response as shown below:

Instead of this

{
"name":"A",
"age":"B"
}


Can it be changed as below?

User{
"name":"A",
"age":"B"
}


But instead of the response starting with JSON, i would like to have the custom name. Can anyone help how to achieve this?

Thanks

Answer

You appear to want to wrap your response in a "wrapper" or "container" class. Given your current class and response looks like this:

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public User Get(int id)
{
    return _userRepository.Find(id);
}

Then you can simply add this wrapper class:

public class UserContainer
{
    public User User { get; set; }
}

And in your controller wrap it:

public UserContainer Get(int id)
{
    var user = _userRepository.Find(id);
    return new UserContainer
    {
        User = user
    }
}

This will make your response look like this:

{
    "User" :
    {
        "Name" : "Foo",
        "Age" : 42
    }
}

But do note that this is semantically unnecessary. The client is already calling the /api/user/42 endpoint, so they'd expect a user back. There's no need to indicate that in your JSON again.

Comments