1

I am trying to convert my object to json, this object has some infinite recursive loop because of some properties, what can I do for not showing or not to convert those properties into json? This kind of error is generating while I'm converting the object into the json.

ERROR

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "$id": "2",
        "Message": "An error has occurred.",
        "ExceptionMessage": "Error getting value from 'userStatus' on 'Bookswap.ViewModels.User'.",
        "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
        "StackTrace": "   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
        "InnerException": {
            "$id": "3",
            "Message": "An error has occurred.",
            "ExceptionMessage": "The SELECT permission was denied on the object 'UserStatus', database 'BOOKSWAP', schema 'dbo'.",
            "ExceptionType": "System.Data.SqlClient.SqlException",
            "StackTrace": "   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader()\r\n   at Bookswap.Models.UserStatusBusinessLayer.get_userStatuses() in D:\\University\\Fall-17\\FYP\\Project\\Web\\Bookswap\\Bookswap\\Models\\UserStatusBusinessLayer.cs:line 19\r\n   at Bookswap.ViewModels.User.get_userStatus() in D:\\University\\Fall-17\\FYP\\Project\\Web\\Bookswap\\Bookswap\\ViewModels\\User.cs:line 40\r\n   at GetuserStatus(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}

User Class

using Bookswap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bookswap.ViewModels
{
    public class User
    {
        public int id { get; set; }

        public string firstName { get; set; }

        public string lastName { get; set; }

        public string email { get; set; }

        public string contact { get; set; }

        public string password { get; set; }

        public string username { get; set; }

        public int cityId { get; set; }

        public int userStatusId { get; set; }

        public int userTypeId { get; set; }

        public DateTime time { get; set; }

        public DateTime dateOfBirth { get; set; }

        public UserStatus userStatus
        {
            get
            {
                UserStatusBusinessLayer us = new UserStatusBusinessLayer();
                return us.userStatuses.FirstOrDefault(x => x.id == userStatusId);
            }
        }

        public UserType userType
        {
            get
            {
                UserTypeBusinessLayer us = new UserTypeBusinessLayer();
                return us.userTypes.FirstOrDefault(x => x.id == userTypeId);
            }
        }

        public Country country
        {
            get
            {
                return new CountryBusinessLayer().countries.FirstOrDefault(x => x.id == (new CityBusinessLayer().cities.FirstOrDefault(y => y.id == cityId).countryId));
            }
        }

        public City city
        {
            get
            {
                return new CityBusinessLayer().cities.FirstOrDefault(y => y.id == cityId);
            }
        }

        public List<UserMedia> userMedia
        {
            get
            {
                return new UserMediaBusinessLayer().userMedias.Where(x => x.userId == id).ToList();
            }
        }

        public List<Book> books
        {
            get
            {
                return new BookBusinessLayer().books.Where(x => x.userId == id).OrderByDescending(x => x.id).ToList();
            }
        }

        public List<Review> reviews
        {
            get
            {
                return new ReviewBusinessLayer().reviews.Where(x => x.userId == id).ToList();
            }
        }

        public int coins
        {
            get
            {
                CoinsBusinessLayer cbl = new CoinsBusinessLayer();
                return cbl.coins.Where(x => x.userId == id).Sum(x => x.coinValue);
            }
        }

        public List<Conversation> conversations
        {
            get
            {
                return new ConversationBusinessLayer().conversations.Where(x => x.useroneid == id || x.usertwoid == id).OrderByDescending(x => x.conversationReplies.OrderByDescending(y => y.time) ).ToList();
            }
        }
    }
}

Web Api Controller Method

public ViewModels.User Post(string identity, string password)
{
    return new Models.UserBusinessLayer().users.FirstOrDefault(x => (x.email == identity && x.password == Data.Crypto.MD5Hash(password)) || (x.username == identity && x.password == Data.Crypto.MD5Hash(password)) || (x.contact == Data.Crypto.RemoveSpaceFromContact(identity) && x.password == Data.Crypto.MD5Hash(password)));
}

2 Answers 2

1

Would JsonIgnore attribute help?

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

1 Comment

Thanks Mate This Works Fine :)
0

the deepest error in your stack is:

"The SELECT permission was denied on the object 'UserStatus', database 'BOOKSWAP', schema 'dbo'."

So I guess you should decide what to do with database permissions, because it could be the key problem in whole stack.

This link should be helpful.

1 Comment

I dont why that error is shown in the deep, i already fixed that.

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.