Serialize() публичный Метод

Serializes the specified Object and writes the Json structure to a Stream using the specified JsonWriter.
public Serialize ( JsonWriter jsonWriter, object value ) : void
jsonWriter JsonWriter The used to write the Json structure.
value object The to serialize.
Результат void
Пример #1
2
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var representation = value as Representation;
            if (representation != null)
                representation.RepopulateHyperMedia();

            var list = (IRepresentationList)value;

            writer.WriteStartObject();
            writer.WritePropertyName("_links");
            serializer.Serialize(writer, list.Links);

            writer.WritePropertyName("_embedded");
            writer.WriteStartObject();
            writer.WritePropertyName(list.Rel);
            writer.WriteStartArray();
            foreach (Representation halResource in list)
            {
                serializer.Serialize(writer, halResource);
            }

            writer.WriteEndArray();
            writer.WriteEndObject();

            var listType = list.GetType();
            var propertyInfos = typeof(RepresentationList<>).GetProperties().Select(p => p.Name);
            foreach (var property in listType.GetProperties().Where(p => !propertyInfos.Contains(p.Name)))
            {
                writer.WritePropertyName(property.Name.ToLower());
                serializer.Serialize(writer, property.GetValue(value, null));
            }

            writer.WriteEndObject();
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var element = (UpdatableElement)value;
            var jsonObject = (JObject)JsonConvert.DeserializeObject(element.SerializedValue);

            //element.SerializedValue
            writer.WriteStartObject();
            foreach (var property in jsonObject.Properties())
            {
                writer.WritePropertyName(property.Name);

                if (UpdatableElement.LastUpdatedFieldName.Equals(property.Name))
                {
                    // let the serializer serialize the value itself
                    serializer.Serialize(writer, element.lastUpdated);
                }
                else
                {
                    // let the serializer serialize the value itself
                    serializer.Serialize(writer, property.Value);
                }
            }
            writer.WriteEndObject();
        }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			ElasticQuery term = (ElasticQuery)value;
			if (term != null)
			{
				writer.WriteStartObject();

				writer.WriteRaw("\"from\": " + term.From);
				writer.WriteRaw(",\"size\": " + term.Size + ",");
				writer.WritePropertyName("query");
				serializer.Serialize(writer, term.Query);

				if (term.Fields != null && term.Fields.Count > 0)
				{
					writer.WritePropertyName("fields");
					writer.WriteStartArray();
					foreach (var field in term.Fields)
					{
						writer.WriteRawValue("\"" + field + "\"");
					}
					writer.WriteEndArray();
				}
				if (term.SortItems != null && term.SortItems.Count > 0)
				{
					writer.WritePropertyName("sort");
					writer.WriteStartObject();
					foreach (var sortItem in term.SortItems)
					{
					    if (sortItem != null)
					    {
					        writer.WritePropertyName(sortItem.FieldName);
					        writer.WriteValue(sortItem.SortType.ToString().ToLower());
					    }
					}

					writer.WriteEndObject();
				}

                //facets
                if (term.Facets != null)
                {
                    writer.WritePropertyName("facets");
                    serializer.Serialize(writer, term.Facets);
                }

                //hightlight
                if(term.Hightlight!=null)
                {
                    writer.WritePropertyName("highlight");
                    serializer.Serialize(writer,term.Hightlight);
                }

                if (term.Explain)
                {
                    writer.WriteRaw(",\"explain\": " + term.Explain.ToString().ToLower());
                }

				writer.WriteEndObject();
			}
		}
        public bool TryWriteFeature(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (!_shapeConverter.CanConvert(ObjectType.Feature))
                return false;

            ObjectType geomType = _shapeConverter.GetObjectType(value);
            if (geomType != ObjectType.Feature)
                return false;

            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue(Enum.GetName(typeof(ObjectType), ObjectType.Feature));

            object id;
            Dictionary<string, object> props;
            var geometry = _shapeConverter.FromFeature(value, out id, out props);

            if (id != null)
            {
                writer.WritePropertyName("id");
                serializer.Serialize(writer, id);
            }

            if (props != null && props.Count > 0)
            {
                writer.WritePropertyName("properties");
                serializer.Serialize(writer, props);
            }

            writer.WritePropertyName("geometry");
            serializer.Serialize(writer, geometry);

            writer.WriteEndObject();
            return true;
        }
Пример #5
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var list = (HalResource)value;

            list.Links.Add(new Link
            {
                Rel = "self",
                Href = list.Href
            });

            writer.WriteStartObject();
            writer.WritePropertyName("_links");
            serializer.Serialize(writer, list.Links);

            writer.WritePropertyName("_embedded");
            writer.WriteStartObject();
            writer.WritePropertyName(list.Rel);
            writer.WriteStartArray();
            foreach (HalResource halResource in (IEnumerable)value)
            {
                serializer.Serialize(writer, halResource);
            }
            writer.WriteEndArray();
            writer.WriteEndObject();
            writer.WriteEndObject();
        }
Пример #6
0
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     var create = value as Network.HistCreateGame;
     EntityDB.Reset();
     foreach (var playerData in create.Players)
     {
         var player = playerData.Player;
         var heroId = 0;
         var controllerId = 0;
         foreach (var tag in player.Tags)
         {
             if (tag.Name == (int)GAME_TAG.HERO_ENTITY)
             {
                 heroId = tag.Value;
             }
             if (tag.Name == (int)GAME_TAG.CONTROLLER)
             {
                 controllerId = tag.Value;
             }
         }
         if (heroId != 0 && controllerId != 0)
         {
             EntityDB.SetHero(controllerId, heroId);
         }
     }
     writer.WriteStartObject();
     writer.WritePropertyName("Game");
     serializer.Serialize(writer, create.Game);
     writer.WritePropertyName("Players");
     serializer.Serialize(writer, create.Players);
     writer.WritePropertyName("Type");
     writer.WriteValue(Enum.GetName(typeof(Network.PowerHistory.PowType), create.Type));
     writer.WriteEndObject();
 }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {

			try {

				serializer = new JsonSerializer {
					ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
					ContractResolver = new DPContractResolver()
				};

				if (ProxyUtil.IsProxiedModelType(value.GetType())) {

					var actualObject = Activator.CreateInstance(ProxyUtil.GetNonProxiedModelType(value.GetType()));
					actualObject.InjectFrom<CloneInjection>(value);

					serializer.Serialize(writer, actualObject);

				} else {

					serializer.Serialize(writer, value);

				}

			} catch (Exception ex) {

				// TODO - log instead of throw, probably throwing an exception trying to 
				// serialize an index, not supported anyways.
				ex.ToString();

			}

		}
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var val = (IColorEffect) value;
            var nameProp = new JProperty("name", val.Name);

            var jobj = new JObject(nameProp);

            var objWriter = jobj.CreateWriter();
            if (value is FixedColor)
            {
                objWriter.WritePropertyName("color");
                serializer.Serialize(objWriter, ((FixedColor) val).Colors[0]);
            }
            if (value is ImageEffect)
            {
                objWriter.WritePropertyName("imageName");
                objWriter.WriteValue(((ImageEffect)value).ImageName);
                objWriter.WritePropertyName("width");
                objWriter.WriteValue(((ImageEffect)value).Width);
            }
            objWriter.WritePropertyName("colors");
            //serializer.Serialize(objWriter, ((ColorFade)val).Colors.Select(c => new JValue(c)));
            serializer.Serialize(objWriter, val.Colors);
            jobj.WriteTo(writer);
        }
Пример #9
0
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var coordinateElements = value as System.Collections.Generic.List<GeoJSON.Net.Geometry.LineString>;
            if (coordinateElements != null && coordinateElements.Count > 0)
            {
                var coordinateArray = new JArray();
                if (coordinateElements[0].Coordinates[0] is GeographicPosition)
                {
                    foreach(var subPolygon in coordinateElements)
                    {
                        var subPolygonCoordinateArray = new JArray();
                        foreach (var coordinates in subPolygon.Coordinates.Select(x => x as GeographicPosition))
                        {
                            var coordinateElement = new JArray(coordinates.Longitude, coordinates.Latitude);
                            if (coordinates.Altitude.HasValue && coordinates.Altitude != 0)
                                coordinateElement = new JArray(coordinates.Longitude, coordinates.Latitude, coordinates.Altitude);

                            subPolygonCoordinateArray.Add(coordinateElement);
                        }
                        coordinateArray.Add(subPolygonCoordinateArray);
                    }
                    serializer.Serialize(writer, coordinateArray);
                }
                else
                    // ToDo: implement
                    throw new NotImplementedException();
            }
            else
                serializer.Serialize(writer, value);
        }
Пример #10
0
        public static void SaveToFile()
        {
            try
            {

                JsonSerializer serializer = new JsonSerializer();
                var prices = dataAccess.GetAllPrices();
                var sales = dataAccess.GetAllSales();
                var priceChanges = dataAccess.GetPriceChanges();

                string path = DataDir + "\\Prices.json";
                var writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, prices);
                writer.Close();

                path = DataDir + "\\Sales.json";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, sales);
                writer.Close();

                path = DataDir + "\\priceChanges.json ";
                writer = new JsonTextWriter(File.CreateText(path));
                serializer.Serialize(writer, priceChanges);
                writer.Close();

            }
            catch (Exception iException)
            {
                int x = 10;
                throw;
            }
        }
        private void writeErrors(ExecutionErrors errors, JsonWriter writer, JsonSerializer serializer)
        {
            if (errors == null || errors.Count == 0)
            {
                return;
            }

            writer.WritePropertyName("errors");

            writer.WriteStartArray();

            errors.Apply(error =>
            {
                writer.WriteStartObject();

                writer.WritePropertyName("message");
                serializer.Serialize(writer, error.Message);

                if (error.Locations != null)
                {
                    writer.WritePropertyName("locations");
                    serializer.Serialize(writer, error.Locations);
                }

                writer.WriteEndObject();
            });

            writer.WriteEndArray();
        }
Пример #12
0
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dataResult = value as DataResult;

            #region 序列化DataResult对象

            writer.WriteStartObject();
            // 写total属性
            writer.WritePropertyName("total");
            serializer.Serialize(writer, dataResult.Total);
            // 写pagecount属性
            writer.WritePropertyName("pagecount");
            serializer.Serialize(writer, dataResult.PageCount);
            // 写pageindex属性
            writer.WritePropertyName("pageindex");
            serializer.Serialize(writer, dataResult.PageIndex);

            // 写rows属性
            var converter = new DataTableConverter();
            writer.WritePropertyName("rows");
            converter.WriteJson(writer, dataResult.Data, serializer);
            writer.WriteEndObject();

            #endregion
    }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var request = value as IMultiGetRequest;
			writer.WriteStartObject();
			if (!(request?.Documents.HasAny()).GetValueOrDefault(false))
			{
				writer.WriteEndObject();
				return;
			}
			var docs = request.Documents.Select(d =>
			{
				if (request.Index != null) d.Index = null;
				if (request.Type != null) d.Type = null;
				return d;
			}).ToList();

			var flatten = docs.All(p => p.CanBeFlattened);

			writer.WritePropertyName(flatten ? "ids" : "docs");
			writer.WriteStartArray();
			foreach (var id in docs)
			{
				if (flatten)
					serializer.Serialize(writer, id.Id);
				else
					serializer.Serialize(writer, id);
			}
			writer.WriteEndArray();
			writer.WriteEndObject();
		}
Пример #14
0
        protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
        {

            var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
            // NOTE: we don't dispose or close these as they would 
            // close the stream, which is used by the rest of the pipeline.
            var writer = default(JsonWriter);

            if (contentHeaders.ContentType.MediaType == "application/bson")
                writer = new BsonWriter(stream);
            else
                writer = new JsonTextWriter(new StreamWriter(stream));

            if (UsesQueryComposition)
            {
                serializer.Serialize(writer, ((IEnumerable)value).OfType<object>().ToList());
            }
            else
            {
                serializer.Serialize(writer, value);
            }

            writer.Flush();

        }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var function = value as IScoreFunction;
			if (function == null) return;

			writer.WriteStartObject();
			{
				if (function.Filter != null)
				{
					writer.WritePropertyName("filter");
					serializer.Serialize(writer, function.Filter);
				}

				var write = WriteDecay(writer, function as IDecayFunction, serializer)
					|| WriteFieldValueFactor(writer, function as IFieldValueFactorFunction, serializer)
					|| WriteRandomScore(writer, function as IRandomScoreFunction, serializer)
					|| WriteScriptScore(writer, function as IScriptScoreFunction, serializer)
					|| WriteWeightFunction(writer, function as IWeightFunction, serializer);
				if (!write) throw new Exception($"Can not write function score json for {function.GetType().Name}");

				if (function.Weight.HasValue)
				{
					writer.WritePropertyName("weight");
					serializer.Serialize(writer, function.Weight.Value);
				}

			}
			writer.WriteEndObject();
		}
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var f = value as IFiltersAggregator;
			if (f == null || f.Filters == null) return;

			writer.WriteStartObject();
			writer.WritePropertyName("filters");

			if (!f.Filters.Any(filter => String.IsNullOrEmpty(filter.FilterName)))
			{
				writer.WriteStartObject();
				foreach (var filter in f.Filters)
				{
					writer.WritePropertyName(filter.FilterName);
					serializer.Serialize(writer, filter);
				}
				writer.WriteEndObject();
			}
			else
			{
				serializer.Serialize(writer, f.Filters);
			}

			writer.WriteEndObject();
		}
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            FeatureCollectionResult fc = (FeatureCollectionResult)value;

            serializer.Converters.Add(new FeatureResultJsonConverter());
            serializer.Converters.Add(new StringEnumConverter());
            //serializer.Converters.Add(new GeometryConverter());

            writer.WriteStartObject();

            if (fc.Id != null){
                writer.WritePropertyName("id");
                writer.WriteValue(fc.Id);
            }

            if (fc.Properties != null) {
                writer.WritePropertyName("properties");
                serializer.Serialize(writer, (fc.Properties));
            }

            if (fc.FeatureResults != null) {
                writer.WritePropertyName("features");
                serializer.Serialize(writer, fc.FeatureResults.ToArray());
            }

            writer.WritePropertyName("type");
            serializer.Serialize(writer, (fc.Type));

            writer.WriteEndObject();
        }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var analysisValue = (AnalysisSettings)value;
			writer.WriteStartObject();
			{
				if (analysisValue.Analyzers.Count > 0)
				{
					writer.WritePropertyName("analyzer");
					serializer.Serialize(writer, analysisValue.Analyzers);
				}

				if (analysisValue.TokenFilters.Count > 0)
				{
					writer.WritePropertyName("filter");
					serializer.Serialize(writer, analysisValue.TokenFilters);
				}

				if (analysisValue.Tokenizers.Count > 0)
				{
					writer.WritePropertyName("tokenizer");
					serializer.Serialize(writer, analysisValue.Tokenizers);
				}

				if (analysisValue.CharFilters.Count > 0)
				{
					writer.WritePropertyName("char_filter");
					serializer.Serialize(writer, analysisValue.CharFilters);
				}
			}
			writer.WriteEndObject();

		}
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var t = value as ITermsQuery;
			if (t == null) return;

			var settings = serializer.GetConnectionSettings();
			var field = settings.Inferrer.Field(t.Field);

			writer.WriteStartObject();
			{
				if (t.Terms.HasAny())
				{
					writer.WritePropertyName(field);
					serializer.Serialize(writer, t.Terms);
				}
				else if (t.TermsLookup != null)
				{
					writer.WritePropertyName(field);
					serializer.Serialize(writer, t.TermsLookup);
				}
				if (t.Boost.HasValue)
				{
					writer.WritePropertyName("boost");
					writer.WriteValue(t.Boost.Value);
				}
				if (!t.Name.IsNullOrEmpty())
				{
					writer.WritePropertyName("_name");
					writer.WriteValue(t.Name);
				}
			}
			writer.WriteEndObject();
		}
Пример #20
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if(!(value is Entry))
            {
                serializer.Serialize(writer, value);
                return;
            }

            Entry entry = (Entry)value;
            writer.WriteStartObject();
            serializer.WriteProperty(writer, Utils.NameOf(() => entry.ContentId), entry.ContentId);
            serializer.WriteProperty(writer, Utils.NameOf(() => entry.RelativePath), entry.RelativePath);
            serializer.WriteProperty(writer, Utils.NameOf(() => entry.IsOpen), entry.IsOpen);
            serializer.WriteProperty(writer, Utils.NameOf(() => entry.Name), entry.Name);
            serializer.WriteProperty(writer, Utils.NameOf(() => entry.Type), entry.Type);

            writer.WritePropertyName(Utils.NameOf(() => entry.Children));
            if (entry.IsOpen)
            {
                serializer.Serialize(writer, entry.Children);
            }
            else
            {
                writer.WriteStartArray();
                writer.WriteEndArray();
            }
            writer.WritePropertyName("has-" + Utils.NameOf(() => entry.Children));
            writer.WriteValue(entry.Children.Count > 0);
            writer.WriteEndObject();
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            FeatureResult f = (FeatureResult)value;

            writer.WriteStartObject();

            if (f.Id != null){
                writer.WritePropertyName("id");
                writer.WriteValue(f.Id);
            }

            if (f.Properties != null) {
                writer.WritePropertyName("properties");
                serializer.Serialize(writer, f.Properties);
            }

            writer.WritePropertyName("type");
            serializer.Serialize(writer, (f.Type));

            if (f.Geometry != null) {
                writer.WritePropertyName("geometry");
                serializer.Serialize(writer, f.Geometry);
            }

            writer.WriteEndObject();
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jsonContract = (JsonObjectContract) serializer.ContractResolver.ResolveContract(value.GetType());

            writer.WriteStartObject();

            foreach (var jsonProp in jsonContract.Properties)
            {
                var propValue = jsonProp.ValueProvider.GetValue(value);
                if (propValue == null && serializer.NullValueHandling == NullValueHandling.Ignore)
                    continue;

                if (jsonProp.PropertyName == "vendorExtensions")
                {
                    var vendorExtensions = (IDictionary<string, object>) propValue;
                    if (vendorExtensions.Any())
                    {
                        foreach (var entry in vendorExtensions)
                        {
                            writer.WritePropertyName(entry.Key);
                            serializer.Serialize(writer, entry.Value);
                        }
                    }
                }
                else
                {
                    writer.WritePropertyName(jsonProp.PropertyName);
                    serializer.Serialize(writer, propValue);
                }
            }

            writer.WriteEndObject();
        }
Пример #23
0
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			if (value == null)
			{
				value = new Color();
			}

			var v = (Color)value;

			writer.WriteStartObject();

			writer.WritePropertyName("r");
			serializer.Serialize(writer, v.r);

			writer.WritePropertyName("g");
			serializer.Serialize(writer, v.g);

			writer.WritePropertyName("b");
			serializer.Serialize(writer, v.b);

			writer.WritePropertyName("a");
			serializer.Serialize(writer, v.a);

			writer.WriteEndObject();
		}
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var val = (IResult)value;

            writer.WriteStartObject();
            if (val.HasValue)
            {
                writer.WritePropertyName("value");
                serializer.Serialize(writer, val.Value);
            }
            else
            {
                writer.WritePropertyName("hasValue");
                writer.WriteValue(false);
            }

            writer.WritePropertyName("wasSuccessful");
            serializer.Serialize(writer, val.WasSuccessful);

            var observations = val.Observations.ToArray();
            if (observations.Length > 0)
            {
                writer.WritePropertyName("observations");
                serializer.Serialize(writer, observations);
            }

            writer.WriteEndObject();
        }
 /// <inheritedoc />
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     if (value == null)
     {
         serializer.Serialize(writer, null);
     }
     else
     {
         var target = (DateTimeOffset)value;
         if (target == null)
         {
             var nullable = (DateTimeOffset?)value;
             if (nullable.HasValue == false)
             {
                 serializer.Serialize(writer, null);
             }
             else
             {
                 serializer.Serialize(writer, nullable.Value.ToString(ImportDateFormat));
             }
         }
         else
         {
             serializer.Serialize(writer, target.ToString(ImportDateFormat));
         }
     }
 }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var request = value as IRegisterPercolatorRequest;

			if (request == null) return;

			writer.WriteStartObject();

			if (request.Query != null)
			{
				writer.WritePropertyName("query");
				serializer.Serialize(writer, request.Query);
			}

			if (request.Metadata != null)
			{
				foreach(var kv in request.Metadata)
				{
					writer.WritePropertyName(kv.Key);
#if DOTNETCORE
					if (kv.Value.GetType().GetTypeInfo().IsValueType)
#else
					if (kv.Value.GetType().IsValueType)
#endif
						writer.WriteValue(kv.Value);
					else
						serializer.Serialize(writer, kv.Value);
				}
			}

			writer.WriteEndObject();
		}
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            NestedFilter term = (NestedFilter)value;
            if (term != null)
            {

                writer.WriteStartObject();
                writer.WritePropertyName("nested");
                writer.WriteStartObject();

                writer.WritePropertyName("path");
                writer.WriteValue(term.Path);
                writer.WritePropertyName("query");
                if(term.Query!=null)
                {
                    serializer.Serialize(writer, term.Query);
                }
                else
                {
                    serializer.Serialize(writer, term.Filter);
                }
//                writer.WritePropertyName("_cache");
//                writer.WriteValue(term.Cache);
                writer.WriteEndObject();
                writer.WriteEndObject();
            }
        }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			CustomFiltersScoreQuery term = (CustomFiltersScoreQuery)value;
			if (term != null)
			{
				writer.WriteStartObject();
				writer.WritePropertyName("custom_filters_score");
				writer.WriteStartObject();
				writer.WritePropertyName("query");
				serializer.Serialize(writer,term.Query);
				writer.WritePropertyName("filters");

				writer.WriteStartArray();
				foreach (var filter in term.Filters)
				{
					serializer.Serialize(writer,filter);
				}
				writer.WriteEndArray();

				writer.WritePropertyName("score_mode");
				writer.WriteValue(term.ScoreMode);

				writer.WritePropertyName("script");
				writer.WriteValue(term.Script);

				writer.WriteEndObject();
				writer.WriteEndObject();
			}
		}
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (NHibernateUtil.IsInitialized(value))
            {
                var proxy = value as INHibernateProxy;
                if (proxy != null)
                {
                    value = proxy.HibernateLazyInitializer.GetImplementation();
                }

                var resolver = serializer.ReferenceResolver;
                if (resolver.IsReferenced(serializer, value))
                {
                    // we've already written the object once; this time, just write the reference
                    // We have to do this manually because we have our own JsonConverter.
                    var valueRef = resolver.GetReference(serializer, value);
                    writer.WriteStartObject();
                    writer.WritePropertyName("$ref");
                    writer.WriteValue(valueRef);
                    writer.WriteEndObject();
                }
                else
                {
                    serializer.Serialize(writer, value);
                }
            }
            else
            {
                serializer.Serialize(writer, null);
            }
        }
Пример #30
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (!(value is SourceFilter))
                throw new SerializeTypeException<SourceFilter>();

            SourceFilter sourceFilter = value as SourceFilter;

            if (sourceFilter.DisableSourceRetrieval)
            {
                serializer.Serialize(writer, false);
            }
            else if (sourceFilter.ExcludeFields == null && sourceFilter.IncludeFields != null)
            {
                if (sourceFilter.IncludeFields.Count(x => !string.IsNullOrWhiteSpace(x)) > 1)
                    serializer.Serialize(writer, sourceFilter.IncludeFields.Where(x => !string.IsNullOrWhiteSpace(x)));
                else
                    serializer.Serialize(writer, sourceFilter.IncludeFields.First(x => !string.IsNullOrWhiteSpace(x)));
            }
            else if (sourceFilter.IncludeFields != null && sourceFilter.ExcludeFields != null)
            {
                Dictionary<string, object> fieldDict = new Dictionary<string, object>();
                fieldDict.Add(_INCLUDE, sourceFilter.IncludeFields.Where(x => !string.IsNullOrWhiteSpace(x)));
                fieldDict.Add(_EXCLUDE, sourceFilter.ExcludeFields.Where(x => !string.IsNullOrWhiteSpace(x)));
                serializer.Serialize(writer, fieldDict);
            }
            else
                throw new Exception("Failed to serialize SourceFilter.");

        }
Пример #31
0
    public void OnBeforeSerialize()
    {
        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
        StringWriter stringWriter = new StringWriter(new StringBuilder());

        serializer.Serialize(stringWriter, _variables, typeof(List <Variable2>));
        _jsonSerializedVariables = stringWriter.GetStringBuilder().ToString();
    }
Пример #32
0
 private void SerializeJsonNetBinaryBenchInner(object o, MemoryStream ms)
 {
     for (int i = 0; i < Iterations; i++)
     {
         var s = new Newtonsoft.Json.JsonSerializer();
         var w = new BsonWriter(ms);
         s.Serialize(w, o);
         Escape(w);
         w.Flush();
     }
 }
Пример #33
0
 private static void Serialize(this Newtonsoft.Json.JsonSerializer jsonSerializer, object model, Stream outputStream, bool withIndentation)
 {
     using (var writer = new StreamWriter(new UnclosableStreamWrapper(outputStream))) {
         using (var jsonWriter = new JsonTextWriter(writer)) {
             jsonWriter.Formatting = withIndentation
                 ? Formatting.Indented
                 : Formatting.None;
             jsonSerializer.Formatting = withIndentation
                 ? Formatting.Indented
                 : Formatting.None;
             jsonSerializer.Serialize(jsonWriter, model);
         }
     }
 }
Пример #34
0
        /// <summary>Serializes an object as JSON to a stream. Will not close the stream.</summary>
        /// <param name="input">Object to serialize.</param>
        /// <param name="outStream">Output stream.</param>
        public void SerializeStream(object input, Stream outStream)
        {
            var serializer   = new Newtonsoft.Json.JsonSerializer();
            var streamWriter = new StreamWriter(
                outStream,
                Encoding.UTF8,
                bufferSize: 4096,
                leaveOpen: true);

            using (JsonWriter jsonWriter = new JsonTextWriter(streamWriter))
            {
                serializer.Serialize(jsonWriter, input);
            }
        }
Пример #35
0
        /// <summary>
        /// 把列表转换为JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static void ToJsonWriter <T>(this IList <T> list, Action <StringWriter> writeAction)
        {
            var jsonSer = new Newtonsoft.Json.JsonSerializer();

            StringWriter sw = new StringWriter();

            using (JsonWriter jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;
                jsonSer.Serialize(jw, list);
                writeAction(sw);
                sw.Close();
            }
        }
Пример #36
0
        public static IHtmlString SerializeObject(object value) {
            using (var stringWriter = new StringWriter())
            using (var jsonWriter = new JsonTextWriter(stringWriter)) {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                jsonWriter.QuoteName = false;
                serializer.Serialize(jsonWriter, value);



                return new HtmlString(stringWriter.ToString());
            }
        }
Пример #37
0
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public String SerializePerson()
    {
        PersonContainer pc = new PersonContainer(this);

        StringBuilder sb = new StringBuilder();
        StringWriter  sw = new StringWriter(sb);

        Newtonsoft.Json.JsonSerializer serializer1 = new Newtonsoft.Json.JsonSerializer();
        Newtonsoft.Json.JsonTextWriter jwriter     = new Newtonsoft.Json.JsonTextWriter(sw);

        serializer1.Serialize(jwriter, pc);

        return(sb.ToString());
    }
Пример #38
0
        public string Serialize(object obj)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    serializer.Serialize(jsonTextWriter, obj);

                    System.Diagnostics.Debug.WriteLine(stringWriter.ToString());

                    return(stringWriter.ToString());
                }
            }
        }
Пример #39
0
        private string BuildDisplayString(IEnumerable <DisplayObject> displayObject)
        {
            StringBuilder markerDisplayString = new StringBuilder();

            using (StringWriter sw = new StringWriter(markerDisplayString))
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    writer.QuoteChar = '\'';

                    Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();
                    ser.Serialize(writer, displayObject);
                }
            return(markerDisplayString.ToString());
        }
Пример #40
0
        protected void TestSerialization <T>(T item, Func <T, T, bool> equalityComparer, string description = "")
        {
            JsonSerializer serializer = BuildSerializer <T>();

            StringBuilder builder = new StringBuilder();
            StringWriter  writer  = new StringWriter(builder);

            serializer.Serialize(writer, item);
            string     result       = builder.ToString();
            JsonReader reader       = new JsonTextReader(new StringReader(result));
            T          deserialized = serializer.Deserialize <T>(reader);

            Assert.True(equalityComparer(item, deserialized), description);
        }
Пример #41
0
        /// <summary>
        /// Serialize the object as JSON
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>JSON as String</returns>
        public string Serialize(object obj)
        {
            using (var stringWriter = new StringWriter())
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar  = '"';

                    _serializer.Serialize(jsonTextWriter, obj);

                    var result = stringWriter.ToString();
                    return(result);
                }
        }
Пример #42
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var ep = value as IPEndPoint;

            if (ep != null)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("Address");
                serializer.Serialize(writer, ep.Address);
                writer.WritePropertyName("Port");
                writer.WriteValue(ep.Port);
                writer.WriteEndObject();
            }
        }
        public void SerializeToStream(System.IO.Stream stream)
        {
            Dictionary <string, object> col = new Dictionary <string, object>();

            col.Add("items", items);

            var baseStream     = new System.IO.MemoryStream();
            var serializer     = new Newtonsoft.Json.JsonSerializer();
            var sw             = new StreamWriter(stream);
            var jsonTextWriter = new JsonTextWriter(sw);

            serializer.Serialize(jsonTextWriter, col);
            jsonTextWriter.Flush();
        }
Пример #44
0
        public HttpContent Serialize(object content, string contentType, Encoding encoding = null)
        {
            if (content == null)
            {
                return(new StringContent(string.Empty, Encoding.UTF8, MediaTypeNames.Text.Plain));
            }

            using var writer     = new StringWriter();
            using var jsonWriter = new JsonTextWriter(writer);
            _serializer.Serialize(jsonWriter, content);
            jsonWriter.Flush();

            return(new StringContent(writer.ToString(), encoding ?? Encoding.UTF8, contentType));
        }
Пример #45
0
        public string Serialize(object obj)
        {
            using (StringWriter stringWriter = new StringWriter())
            {
                using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar  = '"';

                    serializer.Serialize(jsonTextWriter, obj);
                    return(stringWriter.ToString());
                }
            }
        }
Пример #46
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            Query query = value as Query;

            writer.WriteStartObject();
            writer.WritePropertyName("Query");
            serializer.Serialize(writer, query.QueryText);
            //writer.WriteEndObject();
            writer.WritePropertyName("Parameters");
            writer.WriteStartArray();
            if (query.Parameters == null)
            {
                query.Parameters = new List <IParameter>();
            }
            foreach (Parameter parameter in query.Parameters)
            {
                //writer.WriteStartArray();
                serializer.Serialize(writer, parameter);
                //writer.WriteEndObject();
            }
            writer.WriteEndArray();
            writer.WriteEndObject();
        }
Пример #47
0
        /// <summary>
        /// Retutns the JSON string
        /// </summary>
        /// <param name="value">Value to be serialized</param>
        /// <param name="replaceColumnNameWithDefaultNameProperty">Whether replace column name with default property</param>
        /// <returns></returns>
        private static string SerializeToJSON(object value, bool replaceColumnNameWithDefaultNameProperty)
        {
            Type type = value.GetType();

            Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

            json.NullValueHandling = NullValueHandling.Ignore;

            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
            json.MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling  = ReferenceLoopHandling.Ignore;

            if (type == typeof(DataRow))
            {
                json.Converters.Add(new DataRowConverter(replaceColumnNameWithDefaultNameProperty));
            }
            else if (type == typeof(DataTable))
            {
                json.Converters.Add(new DataTableConverter(replaceColumnNameWithDefaultNameProperty));
            }
            else if (type == typeof(DataSet))
            {
                json.Converters.Add(new DataSetConverter(replaceColumnNameWithDefaultNameProperty));
            }

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
            writer.DateFormatHandling   = DateFormatHandling.MicrosoftDateFormat;
            writer.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
            if (FormatJsonOutput)
            {
                writer.Formatting = Formatting.Indented;
            }
            else
            {
                writer.Formatting = Formatting.None;
            }

            writer.QuoteChar = '"';
            json.Serialize(writer, value);

            string output = sw.ToString();

            writer.Close();
            sw.Close();

            return(output);
        }
Пример #48
0
        public void ExportAnimation()
        {
            using (System.Windows.Forms.SaveFileDialog a = new System.Windows.Forms.SaveFileDialog
            {
                FileName = ActionName + ".saanim",
                Filter = "SAModel Animations|*.saanim|JSON|*.json|C structs|*.c"
            })
            {
                if (a.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    switch (System.IO.Path.GetExtension(a.FileName).ToLowerInvariant())
                    {
                    case ".c":
                    case ".txt":
                        using (System.IO.StreamWriter sw = System.IO.File.CreateText(a.FileName))
                        {
                            sw.WriteLine("/* NINJA Motion");
                            sw.WriteLine(" * ");
                            sw.WriteLine(" * Generated by DataToolbox");
                            sw.WriteLine(" * ");
                            sw.WriteLine(" */");
                            sw.WriteLine();
                            GeoAnim.Animation.ToStructVariables(sw);
                            sw.Flush();
                            sw.Close();
                        }
                        break;

                    case ".json":
                        Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer()
                        {
                            Culture = System.Globalization.CultureInfo.InvariantCulture
                        };
                        using (TextWriter tw = File.CreateText(a.FileName))
                            using (JsonTextWriter jtw = new JsonTextWriter(tw)
                            {
                                Formatting = Formatting.Indented
                            })
                                js.Serialize(jtw, GeoAnim.Animation);
                        break;

                    case ".saanim":
                    default:
                        GeoAnim.Animation.Save(a.FileName);
                        break;
                    }
                }
            }
        }
Пример #49
0
        public void Save(Product productChanged)
        {
            List <Product> changedProducts = new List <Product>();
            string         getAll          = File.ReadAllText(@"products.json");

            JsonConvert.PopulateObject(getAll, changedProducts);
            //Byta "Towel" produkt med "Handkerchief":
            //productChanged.Name[2] = "Handkerchief";
            //Spara filen igen i json fil:
            using (StreamWriter savedFile = File.CreateText(@"products.json"))
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                serializer.Serialize(savedFile, productChanged);
            }
        }
Пример #50
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var data = value as DataItem;

            if (data != null)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("Type");
                writer.WriteValue(data.Type);
                writer.WritePropertyName("Value");
                serializer.Converters.Add(new DataTableConverter());
                serializer.Serialize(writer, data.Value);
                writer.WriteEndObject();
            }
        }
Пример #51
0
        /// <summary>
        ///     Writes the json.
        /// </summary>
        /// <param name="writer">JsonWriter</param>
        /// <param name="dataRow">dataRow</param>
        /// <param name="ser">JsonSerializer</param>
        public override void WriteJson(JsonWriter writer, object dataRow, Newtonsoft.Json.JsonSerializer ser)
        {
            var row = dataRow as DataRow;

            writer.WriteStartObject();
            if (row != null)
            {
                foreach (DataColumn column in row.Table.Columns)
                {
                    writer.WritePropertyName(column.ColumnName);
                    ser.Serialize(writer, row[column]);
                }
            }
            writer.WriteEndObject();
        }
Пример #52
0
        public Task <byte[]> Serialize <TValue>(TValue value)
        {
            var sb = new StringBuilder(256);

            var sw = new StringWriter(sb, CultureInfo.InvariantCulture);

            using (var jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = _jsonSerializer.Formatting;

                _jsonSerializer.Serialize(jsonWriter, value, typeof(TValue));
            }

            return(Task.FromResult(_encoding.GetBytes(sw.ToString())));
        }
Пример #53
0
        public string Serialize(object obj)
        {
            using var stringWriter   = new StringWriter();
            using var jsonTextWriter = new JsonTextWriter(stringWriter)
                  {
                      Formatting = Formatting.Indented,
                      QuoteChar  = '"'
                  };

            serializer.Serialize(jsonTextWriter, obj);

            var result = stringWriter.ToString();

            return(result);
        }
Пример #54
0
        protected void TestConverter <T>(T item, Func <T, T, bool> equalityComparer, JsonConverter <T> converter)
        {
            JsonSerializer serializer = new JsonSerializer();

            serializer.Converters.Add(converter);
            StringBuilder builder = new StringBuilder();
            StringWriter  writer  = new StringWriter(builder);

            serializer.Serialize(writer, item);
            string     result       = builder.ToString();
            JsonReader reader       = new JsonTextReader(new StringReader(result));
            T          deserialized = serializer.Deserialize <T>(reader);

            Assert.True(equalityComparer(item, deserialized));
        }
Пример #55
0
        public static JObject GetYamlToJson(string location)
        {
            var r            = new StringReader(location);
            var deserializer = new Deserializer( );
            var yamlObject   = deserializer.Deserialize(r);
            var serializer   = new Newtonsoft.Json.JsonSerializer( );
            var w            = new StringWriter( );

            serializer.Serialize(w, yamlObject);
            string  jsonText  = w.ToString( );
            JArray  jsonArray = JArray.Parse(jsonText);
            JObject json      = JObject.Parse(jsonArray[0].ToString( ));

            return(json);
        }
Пример #56
0
        public byte[] serialization(List <Hotel> hotels)
        {
            var ser = new Newtonsoft.Json.JsonSerializer();

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    ser.Serialize(streamWriter, hotels);

                    streamWriter.Flush();
                }
                return(memoryStream.ToArray());
            }
        }
Пример #57
0
        public async Task InvokeAsync(HttpContext httpContext, IStudentServiceDb service)
        {
            if (httpContext.Request != null)
            {
                httpContext.Request.EnableBuffering();
                string BodyBuffer = "";
                using (StreamReader reader = new StreamReader(httpContext.Request.Body))
                {
                    BodyBuffer = await reader.ReadToEndAsync();

                    httpContext.Request.Body.Position = 0;
                }

                var log = new Log
                {
                    Path   = httpContext.Request.Path,
                    Method = httpContext.Request.Method,
                    Query  = httpContext.Request.QueryString.ToString(),
                    Body   = BodyBuffer,
                    Time   = DateTime.UtcNow
                };

                using (StreamWriter writer = File.AppendText("Log.txt"))
                {
                    string LogString = "TIME : " + log.Time + "\n" + "PATH: " + log.Path + "\n" + "METHOD: " + log.Method + "\n" + "QUERY: " + log.Query + "\n" + "BODY: " + log.Body + "\n\n\n";

                    writer.Write(LogString);

                    writer.Flush();
                    writer.Close();
                }

                var serializer   = new Newtonsoft.Json.JsonSerializer();
                var stringWriter = new StringWriter();
                using (var writer = new JsonTextWriter(stringWriter))
                {
                    writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                    writer.QuoteName  = false;
                    serializer.Serialize(writer, log);
                }
                var jsonString = stringWriter.ToString();
                File.AppendAllText($"Log.json", jsonString);
            }
            if (_next != null)
            {
                await _next(httpContext);
            }
        }
Пример #58
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var dataSource = value as DataSource;

            if (dataSource != null)
            {
                serializer.Converters.Add(new DataItemJsonConverter());
                writer.WriteStartObject();
                foreach (var item in dataSource)
                {
                    writer.WritePropertyName(item.Key);
                    serializer.Serialize(writer, item.Value);
                }
                writer.WriteEndObject();
            }
        }
Пример #59
0
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var objHasValue = (bool)value.GetType().GetProperty("HasValue").GetValue(value, null);

            if (objHasValue)
            {
                //If it has a value then it serializes it into the same object
                var objValue = value.GetType().GetProperty("Value").GetValue(value, null);
                serializer.Serialize(writer, objValue);
            }
            else
            {
                //If it doesn't have a value, then it serializes it into null
                writer.WriteToken(JsonToken.Null);
            }
        }
Пример #60
0
        public virtual string SerializeJson(object instance, Type type)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar  = '"';

                    _serializer.Serialize(jsonTextWriter, instance);

                    var result = stringWriter.ToString();
                    return(result);
                }
            }
        }