Beispiel #1
0
        /// <summary>
        /// grabs the Field/PropertyInfo of <paramref name="obj"/> for <paramref name="key"/> and sets it
        /// with the next element in the JSON string.
        /// </summary>
        /// <param name="obj">Object.</param>
        /// <param name="key">Key.</param>
        void SetNextValueOnObject(ref object obj, string key)
        {
            var field = _cacheResolver.GetField(obj.GetType(), key);

            if (field != null)
            {
                if (_cacheResolver.IsMemberInfoEncodeableOrDecodeable(field, field.IsPublic))
                {
                    var value = DecodeValue(GetNextToken(), field.FieldType);
                    if (obj.GetType().IsValueType)
                    {
                        // obj is a struct.
                        var instanceRef = obj;
                        field.SetValue(instanceRef, value);
                        obj = instanceRef;
                        return;
                    }

                    // obj is a class.
                    field.SetValue(obj, value);
                    return;
                }
            }

            // we still need to eat the value even if we didnt set it so the parser is in the right spot
            var orhpanedValue = DecodeValueUntyped(GetNextToken());

            // check for a NsonConverter and use it if we have one
            var converter = _settings?.GetTypeConverterForType(obj.GetType());

            if (converter != null && converter.CanRead)
            {
                converter.OnFoundCustomData(ref obj, key, orhpanedValue);
            }
        }
        /// <summary>
        /// encodes an object to the nson stream.
        /// </summary>
        public void EncodeObject(object value)
        {
            Type type = value.GetType();

            WriteStartObject(type.FullName);

            // if this returns true, we have a reference so we are done
            if (WriteOptionalReferenceData(value))
            {
                WriteEndObject();
                return;
            }

            // check for an override converter and use it if present
            NsonTypeConverter converter = _settings.GetTypeConverterForType(type);

            if (converter != null && converter.CanWrite)
            {
                converter.WriteNson(this, value);
                if (converter.WantsExclusiveWrite)
                {
                    WriteEndObject();
                    return;
                }
            }

            foreach (System.Reflection.FieldInfo field in _cacheResolver.GetEncodableFieldsForType(type))
            {
                WriteValueDelimiter();
                EncodeString(field.Name, true);
                AppendColon();
                EncodeValue(field.GetValue(value));
            }

            WriteEndObject();
        }