Пример #1
0
        public JObject Serialize(JsonSerializer serializer)
        {
            serializer.ContractResolver = new JsonApiContractResolver(_propertyNameConverter);
            _serializer = serializer;

            _sourceSerializer = JsonApiSerializer.GetJsonSerializer(_serializer.Converters);
            _sourceSerializer.ContractResolver = new SourceContractResolver(_propertyNameConverter, _resource);

            if (_value == null)
            {
                return(SerializeNull());
            }

            var graph           = new ResourceGraph(_value, _resource, _includedGraphPaths);
            var dataSection     = SerializeData(graph);
            var includesSection = SerializeIncludes(graph);
            var metaSection     = SerializeMetadata();

            var result = new JObject
            {
                ["data"] = dataSection
            };

            var    isCollection = _value.IsCollectionType();
            string id           = null;

            if (!isCollection)
            {
                id = dataSection["id"]?.ToString();
            }

            var links = CreateTopLevelLinks(dataSection is JArray ? dataSection.Count() : 0, id);

            if (links.HasValues)
            {
                result.Add("links", links);
            }

            if (includesSection != null && includesSection.Count > 0)
            {
                result["included"] = includesSection;
            }

            if (metaSection != null)
            {
                result["meta"] = metaSection;
            }

            return(result);
        }