2

1) I have a WebAPI method, which returns object User. All fields of this object in callback of ajax call starting with uppercase. I'm trying to achieve camelCase in result. I do not want to write [JsonProperty] before each field, but ContractResolver = new CamelCasePropertyNamesContractResolver(); doesn't working properly. I can't understand why.
2) In class UserList (see below) i have a link to User. When i'm trying to return UserList or User as a result of WebAPI method i'm getting an error about "self referencing loop". But i've written in configuration config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; - why it's not working? And i do not want to write [JsonIgnore] in every such case.

WebApiConfig.cs:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
    }
}

Returning User object from controller:

var user = Data.GetUserByUserName(userName);

return Json<object>(new
        {
            success = true,
            user = user
        });

User class:

public class User : BaseEntity
{
    public string Login { get; set; }

    public string Email { get; set; }

    public List<UserList> UserLists { get; set; }

    public string AvatarFileID { get; set; }
    public int? AvatarFileProviderID { get; set; }
}

1 Answer 1

1

The answer to your 1st question is to simply return the object and not Json (or even more correctly - return a HttpResponse with the object included)

The answer to the second question: do not send your original models to the client, use ViewModels instead and pass only the properties that are needed (for example, in the front-end you may need only the users' names, and not the whole user objects)

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

2 Comments

About second question: Model contains only needed data in this case... I think it's not the better solution to duplicate class only to get separate viewmodel. And anyway serializing do not works properly.
The second proble are gone too, when i've changed json<object> to simply returning object.

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.