Repository: JamesNK/Newtonsoft.Json
Branch: master
Commit: 4f73e7437244
Files: 1163
Total size: 14.7 MB
Directory structure:
gitextract_wyahh53l/
├── .gitattributes
├── .github/
│ └── workflows/
│ └── codeql.yml
├── .gitignore
├── Build/
│ ├── Sign-Package.ps1
│ ├── appsettings.json
│ ├── build.ps1
│ ├── localbuild.ps1
│ ├── psake.psm1
│ ├── runbuild.cmd
│ ├── runbuild.ps1
│ └── version.json
├── CONTRIBUTING.md
├── Doc/
│ ├── ConditionalProperties.aml
│ ├── ContractResolver.aml
│ ├── ConvertingJSONandXML.aml
│ ├── CreatingLINQtoJSON.aml
│ ├── CustomCreationConverter.aml
│ ├── DatesInJSON.aml
│ ├── Introduction.aml
│ ├── JsonNetVsDotNetSerializers.aml
│ ├── JsonSchema.aml
│ ├── LINQtoJSON.aml
│ ├── ParsingLINQtoJSON.aml
│ ├── Performance.aml
│ ├── PreserveObjectReferences.aml
│ ├── QueryingLINQtoJSON.aml
│ ├── ReadingWritingJSON.aml
│ ├── ReducingSerializedJSONSize.aml
│ ├── Samples/
│ │ ├── Bson/
│ │ │ ├── DeserializeFromBson.aml
│ │ │ ├── DeserializeFromBsonCollection.aml
│ │ │ └── SerializeToBson.aml
│ │ ├── Json/
│ │ │ ├── CustomJsonReader.aml
│ │ │ ├── CustomJsonWriter.aml
│ │ │ ├── ReadJsonWithJsonTextReader.aml
│ │ │ ├── ReadMultipleContentWithJsonReader.aml
│ │ │ └── WriteJsonWithJsonTextWriter.aml
│ │ ├── JsonPath/
│ │ │ ├── ErrorWhenNoMatchQuery.aml
│ │ │ ├── QueryJsonSelectToken.aml
│ │ │ ├── QueryJsonSelectTokenEscaped.aml
│ │ │ ├── QueryJsonSelectTokenJsonPath.aml
│ │ │ ├── QueryJsonSelectTokenWithLinq.aml
│ │ │ ├── RegexQuery.aml
│ │ │ └── StrictEqualsQuery.aml
│ │ ├── Linq/
│ │ │ ├── Clone.aml
│ │ │ ├── CreateJsonAnonymousObject.aml
│ │ │ ├── CreateJsonCollectionInitializer.aml
│ │ │ ├── CreateJsonDeclaratively.aml
│ │ │ ├── CreateJsonDynamic.aml
│ │ │ ├── CreateJsonJTokenWriter.aml
│ │ │ ├── CreateJsonManually.aml
│ │ │ ├── CreateReader.aml
│ │ │ ├── CreateWriter.aml
│ │ │ ├── DeepEquals.aml
│ │ │ ├── DeserializeWithLinq.aml
│ │ │ ├── FromObject.aml
│ │ │ ├── JObjectProperties.aml
│ │ │ ├── JTokenAnnotation.aml
│ │ │ ├── JValueCast.aml
│ │ │ ├── JValueValue.aml
│ │ │ ├── MergeJson.aml
│ │ │ ├── ModifyJson.aml
│ │ │ ├── ParseJsonAny.aml
│ │ │ ├── ParseJsonArray.aml
│ │ │ ├── ParseJsonObject.aml
│ │ │ ├── QueryJson.aml
│ │ │ ├── QueryJsonDynamic.aml
│ │ │ ├── QueryJsonLinq.aml
│ │ │ ├── ReadJTokenFromBson.aml
│ │ │ ├── ReadJson.aml
│ │ │ ├── SerializeWithLinq.aml
│ │ │ ├── ToObjectComplex.aml
│ │ │ ├── ToObjectGeneric.aml
│ │ │ ├── ToObjectType.aml
│ │ │ ├── ToString.aml
│ │ │ ├── ToStringJsonConverter.aml
│ │ │ ├── WriteJTokenToBson.aml
│ │ │ └── WriteToJsonFile.aml
│ │ ├── Samples.aml
│ │ ├── Schema/
│ │ │ ├── CreateJsonSchemaManually.aml
│ │ │ ├── JTokenIsValid.aml
│ │ │ ├── JTokenIsValidWithMessages.aml
│ │ │ ├── JTokenValidateWithEvent.aml
│ │ │ ├── JsonSchemaParse.aml
│ │ │ ├── JsonValidatingReaderAndSerializer.aml
│ │ │ ├── LoadJsonSchemaFromFile.aml
│ │ │ ├── RefJsonSchemaResolver.aml
│ │ │ └── SaveJsonSchemaToFile.aml
│ │ ├── Serializer/
│ │ │ ├── CustomContractResolver.aml
│ │ │ ├── CustomJsonConverter.aml
│ │ │ ├── CustomJsonConverterGeneric.aml
│ │ │ ├── CustomTraceWriter.aml
│ │ │ ├── DataContractAndDataMember.aml
│ │ │ ├── DefaultSettings.aml
│ │ │ ├── DefaultValueAttributeIgnore.aml
│ │ │ ├── DefaultValueHandlingIgnore.aml
│ │ │ ├── DeserializeAnonymousType.aml
│ │ │ ├── DeserializeCollection.aml
│ │ │ ├── DeserializeConstructorHandling.aml
│ │ │ ├── DeserializeCustomCreationConverter.aml
│ │ │ ├── DeserializeDataSet.aml
│ │ │ ├── DeserializeDateFormatString.aml
│ │ │ ├── DeserializeDictionary.aml
│ │ │ ├── DeserializeExtensionData.aml
│ │ │ ├── DeserializeImmutableCollections.aml
│ │ │ ├── DeserializeMetadataPropertyHandling.aml
│ │ │ ├── DeserializeMissingMemberHandling.aml
│ │ │ ├── DeserializeObject.aml
│ │ │ ├── DeserializeObjectCreationHandling.aml
│ │ │ ├── DeserializeWithDependencyInjection.aml
│ │ │ ├── DeserializeWithJsonSerializerFromFile.aml
│ │ │ ├── ErrorHandlingAttribute.aml
│ │ │ ├── ErrorHandlingEvent.aml
│ │ │ ├── JsonConstructorAttribute.aml
│ │ │ ├── JsonConverterAttributeClass.aml
│ │ │ ├── JsonConverterAttributeProperty.aml
│ │ │ ├── JsonObjectAttributeOptIn.aml
│ │ │ ├── JsonObjectAttributeOverrideIEnumerable.aml
│ │ │ ├── JsonPropertyItemLevelSetting.aml
│ │ │ ├── JsonPropertyName.aml
│ │ │ ├── JsonPropertyOrder.aml
│ │ │ ├── JsonPropertyPropertyLevelSetting.aml
│ │ │ ├── JsonPropertyRequired.aml
│ │ │ ├── MaxDepth.aml
│ │ │ ├── NamingStrategyAttributes.aml
│ │ │ ├── NamingStrategyCamelCase.aml
│ │ │ ├── NamingStrategySkipDictionaryKeys.aml
│ │ │ ├── NamingStrategySkipSpecifiedNames.aml
│ │ │ ├── NamingStrategySnakeCase.aml
│ │ │ ├── NullValueHandlingIgnore.aml
│ │ │ ├── PopulateObject.aml
│ │ │ ├── PreserveReferencesHandlingObject.aml
│ │ │ ├── PropertyJsonIgnore.aml
│ │ │ ├── ReferenceLoopHandlingIgnore.aml
│ │ │ ├── SerializationCallbackAttributes.aml
│ │ │ ├── SerializeCollection.aml
│ │ │ ├── SerializeConditionalProperty.aml
│ │ │ ├── SerializeContractResolver.aml
│ │ │ ├── SerializeDataSet.aml
│ │ │ ├── SerializeDateFormatHandling.aml
│ │ │ ├── SerializeDateFormatString.aml
│ │ │ ├── SerializeDateTimeZoneHandling.aml
│ │ │ ├── SerializeDictionary.aml
│ │ │ ├── SerializeExtensionData.aml
│ │ │ ├── SerializeImmutableCollections.aml
│ │ │ ├── SerializeObject.aml
│ │ │ ├── SerializeRawJson.aml
│ │ │ ├── SerializeSerializationBinder.aml
│ │ │ ├── SerializeTypeNameHandling.aml
│ │ │ ├── SerializeUnindentedJson.aml
│ │ │ ├── SerializeWithJsonConverters.aml
│ │ │ ├── SerializeWithJsonSerializerToFile.aml
│ │ │ └── TraceWriter.aml
│ │ └── Xml/
│ │ ├── ConvertJsonToXml.aml
│ │ ├── ConvertXmlToJson.aml
│ │ └── ConvertXmlToJsonForceArray.aml
│ ├── SelectToken.aml
│ ├── SerializationAttributes.aml
│ ├── SerializationCallbacks.aml
│ ├── SerializationErrorHandling.aml
│ ├── SerializationGuide.aml
│ ├── SerializationSettings.aml
│ ├── SerializationTracing.aml
│ ├── SerializingCollections.aml
│ ├── SerializingJSON.aml
│ ├── SerializingJSONFragments.aml
│ ├── doc.content
│ ├── doc.shfbproj
│ ├── license.txt
│ └── readme.txt
├── ISSUE_TEMPLATE.md
├── LICENSE.md
├── README.md
├── Src/
│ ├── Directory.Build.props
│ ├── Newtonsoft.Json/
│ │ ├── Bson/
│ │ │ ├── BsonBinaryType.cs
│ │ │ ├── BsonBinaryWriter.cs
│ │ │ ├── BsonObjectId.cs
│ │ │ ├── BsonReader.cs
│ │ │ ├── BsonToken.cs
│ │ │ ├── BsonType.cs
│ │ │ └── BsonWriter.cs
│ │ ├── CompatibilitySuppressions.xml
│ │ ├── ConstructorHandling.cs
│ │ ├── Converters/
│ │ │ ├── BinaryConverter.cs
│ │ │ ├── BsonObjectIdConverter.cs
│ │ │ ├── CustomCreationConverter.cs
│ │ │ ├── DataSetConverter.cs
│ │ │ ├── DataTableConverter.cs
│ │ │ ├── DateTimeConverterBase.cs
│ │ │ ├── DiscriminatedUnionConverter.cs
│ │ │ ├── EntityKeyMemberConverter.cs
│ │ │ ├── ExpandoObjectConverter.cs
│ │ │ ├── IsoDateTimeConverter.cs
│ │ │ ├── JavaScriptDateTimeConverter.cs
│ │ │ ├── KeyValuePairConverter.cs
│ │ │ ├── RegexConverter.cs
│ │ │ ├── StringEnumConverter.cs
│ │ │ ├── UnixDateTimeConverter.cs
│ │ │ ├── VersionConverter.cs
│ │ │ └── XmlNodeConverter.cs
│ │ ├── DateFormatHandling.cs
│ │ ├── DateParseHandling.cs
│ │ ├── DateTimeZoneHandling.cs
│ │ ├── DefaultJsonNameTable.cs
│ │ ├── DefaultValueHandling.cs
│ │ ├── Dynamic.snk
│ │ ├── FloatFormatHandling.cs
│ │ ├── FloatParseHandling.cs
│ │ ├── FormatterAssemblyStyle.cs
│ │ ├── Formatting.cs
│ │ ├── IArrayPool.cs
│ │ ├── IJsonLineInfo.cs
│ │ ├── JsonArrayAttribute.cs
│ │ ├── JsonConstructorAttribute.cs
│ │ ├── JsonContainerAttribute.cs
│ │ ├── JsonConvert.cs
│ │ ├── JsonConverter.cs
│ │ ├── JsonConverterAttribute.cs
│ │ ├── JsonConverterCollection.cs
│ │ ├── JsonDictionaryAttribute.cs
│ │ ├── JsonException.cs
│ │ ├── JsonExtensionDataAttribute.cs
│ │ ├── JsonIgnoreAttribute.cs
│ │ ├── JsonNameTable.cs
│ │ ├── JsonObjectAttribute.cs
│ │ ├── JsonPosition.cs
│ │ ├── JsonPropertyAttribute.cs
│ │ ├── JsonReader.Async.cs
│ │ ├── JsonReader.cs
│ │ ├── JsonReaderException.cs
│ │ ├── JsonRequiredAttribute.cs
│ │ ├── JsonSerializationException.cs
│ │ ├── JsonSerializer.cs
│ │ ├── JsonSerializerSettings.cs
│ │ ├── JsonTextReader.Async.cs
│ │ ├── JsonTextReader.cs
│ │ ├── JsonTextWriter.Async.cs
│ │ ├── JsonTextWriter.cs
│ │ ├── JsonToken.cs
│ │ ├── JsonValidatingReader.cs
│ │ ├── JsonWriter.Async.cs
│ │ ├── JsonWriter.cs
│ │ ├── JsonWriterException.cs
│ │ ├── Linq/
│ │ │ ├── CommentHandling.cs
│ │ │ ├── DuplicatePropertyNameHandling.cs
│ │ │ ├── Extensions.cs
│ │ │ ├── IJEnumerable.cs
│ │ │ ├── JArray.Async.cs
│ │ │ ├── JArray.cs
│ │ │ ├── JConstructor.Async.cs
│ │ │ ├── JConstructor.cs
│ │ │ ├── JContainer.Async.cs
│ │ │ ├── JContainer.cs
│ │ │ ├── JEnumerable.cs
│ │ │ ├── JObject.Async.cs
│ │ │ ├── JObject.cs
│ │ │ ├── JProperty.Async.cs
│ │ │ ├── JProperty.cs
│ │ │ ├── JPropertyDescriptor.cs
│ │ │ ├── JPropertyKeyedCollection.cs
│ │ │ ├── JRaw.Async.cs
│ │ │ ├── JRaw.cs
│ │ │ ├── JToken.Async.cs
│ │ │ ├── JToken.cs
│ │ │ ├── JTokenEqualityComparer.cs
│ │ │ ├── JTokenReader.cs
│ │ │ ├── JTokenType.cs
│ │ │ ├── JTokenWriter.Async.cs
│ │ │ ├── JTokenWriter.cs
│ │ │ ├── JValue.Async.cs
│ │ │ ├── JValue.cs
│ │ │ ├── JsonCloneSettings.cs
│ │ │ ├── JsonLoadSettings.cs
│ │ │ ├── JsonMergeSettings.cs
│ │ │ ├── JsonPath/
│ │ │ │ ├── ArrayIndexFilter.cs
│ │ │ │ ├── ArrayMultipleIndexFilter.cs
│ │ │ │ ├── ArraySliceFilter.cs
│ │ │ │ ├── FieldFilter.cs
│ │ │ │ ├── FieldMultipleFilter.cs
│ │ │ │ ├── JPath.cs
│ │ │ │ ├── PathFilter.cs
│ │ │ │ ├── QueryExpression.cs
│ │ │ │ ├── QueryFilter.cs
│ │ │ │ ├── QueryScanFilter.cs
│ │ │ │ ├── RootFilter.cs
│ │ │ │ ├── ScanFilter.cs
│ │ │ │ └── ScanMultipleFilter.cs
│ │ │ ├── JsonSelectSettings.cs
│ │ │ ├── LineInfoHandling.cs
│ │ │ ├── MergeArrayHandling.cs
│ │ │ └── MergeNullValueHandling.cs
│ │ ├── MemberSerialization.cs
│ │ ├── MetadataPropertyHandling.cs
│ │ ├── MissingMemberHandling.cs
│ │ ├── Newtonsoft.Json.csproj
│ │ ├── Newtonsoft.Json.ruleset
│ │ ├── NullValueHandling.cs
│ │ ├── ObjectCreationHandling.cs
│ │ ├── PreserveReferencesHandling.cs
│ │ ├── Properties/
│ │ │ └── AssemblyInfo.cs
│ │ ├── README.md
│ │ ├── ReferenceLoopHandling.cs
│ │ ├── Required.cs
│ │ ├── Schema/
│ │ │ ├── Extensions.cs
│ │ │ ├── JsonSchema.cs
│ │ │ ├── JsonSchemaBuilder.cs
│ │ │ ├── JsonSchemaConstants.cs
│ │ │ ├── JsonSchemaException.cs
│ │ │ ├── JsonSchemaGenerator.cs
│ │ │ ├── JsonSchemaModel.cs
│ │ │ ├── JsonSchemaModelBuilder.cs
│ │ │ ├── JsonSchemaNode.cs
│ │ │ ├── JsonSchemaNodeCollection.cs
│ │ │ ├── JsonSchemaResolver.cs
│ │ │ ├── JsonSchemaType.cs
│ │ │ ├── JsonSchemaWriter.cs
│ │ │ ├── UndefinedSchemaIdHandling.cs
│ │ │ ├── ValidationEventArgs.cs
│ │ │ └── ValidationEventHandler.cs
│ │ ├── Serialization/
│ │ │ ├── CachedAttributeGetter.cs
│ │ │ ├── CamelCaseNamingStrategy.cs
│ │ │ ├── CamelCasePropertyNamesContractResolver.cs
│ │ │ ├── DefaultContractResolver.cs
│ │ │ ├── DefaultNamingStrategy.cs
│ │ │ ├── DefaultReferenceResolver.cs
│ │ │ ├── DefaultSerializationBinder.cs
│ │ │ ├── DiagnosticsTraceWriter.cs
│ │ │ ├── DynamicValueProvider.cs
│ │ │ ├── ErrorContext.cs
│ │ │ ├── ErrorEventArgs.cs
│ │ │ ├── ExpressionValueProvider.cs
│ │ │ ├── FormatterConverter.cs
│ │ │ ├── IAttributeProvider.cs
│ │ │ ├── IContractResolver.cs
│ │ │ ├── IReferenceResolver.cs
│ │ │ ├── ISerializationBinder.cs
│ │ │ ├── ITraceWriter.cs
│ │ │ ├── IValueProvider.cs
│ │ │ ├── JsonArrayContract.cs
│ │ │ ├── JsonContainerContract.cs
│ │ │ ├── JsonContract.cs
│ │ │ ├── JsonDictionaryContract.cs
│ │ │ ├── JsonDynamicContract.cs
│ │ │ ├── JsonFormatterConverter.cs
│ │ │ ├── JsonISerializableContract.cs
│ │ │ ├── JsonLinqContract.cs
│ │ │ ├── JsonObjectContract.cs
│ │ │ ├── JsonPrimitiveContract.cs
│ │ │ ├── JsonProperty.cs
│ │ │ ├── JsonPropertyCollection.cs
│ │ │ ├── JsonSerializerInternalBase.cs
│ │ │ ├── JsonSerializerInternalReader.cs
│ │ │ ├── JsonSerializerInternalWriter.cs
│ │ │ ├── JsonSerializerProxy.cs
│ │ │ ├── JsonStringContract.cs
│ │ │ ├── JsonTypeReflector.cs
│ │ │ ├── KebabCaseNamingStrategy.cs
│ │ │ ├── MemoryTraceWriter.cs
│ │ │ ├── NamingStrategy.cs
│ │ │ ├── ObjectConstructor.cs
│ │ │ ├── OnErrorAttribute.cs
│ │ │ ├── ReflectionAttributeProvider.cs
│ │ │ ├── ReflectionValueProvider.cs
│ │ │ ├── SerializationBinderAdapter.cs
│ │ │ ├── SnakeCaseNamingStrategy.cs
│ │ │ ├── TraceJsonReader.cs
│ │ │ └── TraceJsonWriter.cs
│ │ ├── SerializationBinder.cs
│ │ ├── StringEscapeHandling.cs
│ │ ├── TraceLevel.cs
│ │ ├── TypeNameAssemblyFormatHandling.cs
│ │ ├── TypeNameHandling.cs
│ │ ├── Utilities/
│ │ │ ├── AsyncUtils.cs
│ │ │ ├── Base64Encoder.cs
│ │ │ ├── BidirectionalDictionary.cs
│ │ │ ├── BoxedPrimitives.cs
│ │ │ ├── CollectionUtils.cs
│ │ │ ├── CollectionWrapper.cs
│ │ │ ├── ConvertUtils.cs
│ │ │ ├── DateTimeParser.cs
│ │ │ ├── DateTimeUtils.cs
│ │ │ ├── DictionaryWrapper.cs
│ │ │ ├── DynamicProxy.cs
│ │ │ ├── DynamicProxyMetaObject.cs
│ │ │ ├── DynamicReflectionDelegateFactory.cs
│ │ │ ├── DynamicUtils.cs
│ │ │ ├── DynamicallyAccessedMemberTypes.cs
│ │ │ ├── DynamicallyAccessedMembersAttribute.cs
│ │ │ ├── EnumInfo.cs
│ │ │ ├── EnumUtils.cs
│ │ │ ├── ExpressionReflectionDelegateFactory.cs
│ │ │ ├── FSharpUtils.cs
│ │ │ ├── FeatureGuardAttribute.cs
│ │ │ ├── FeatureSwitchDefinitionAttribute.cs
│ │ │ ├── ILGeneratorExtensions.cs
│ │ │ ├── ImmutableCollectionsUtils.cs
│ │ │ ├── JavaScriptUtils.cs
│ │ │ ├── JsonTokenUtils.cs
│ │ │ ├── LateBoundReflectionDelegateFactory.cs
│ │ │ ├── LinqBridge.cs
│ │ │ ├── MathUtils.cs
│ │ │ ├── MethodBinder.cs
│ │ │ ├── MethodCall.cs
│ │ │ ├── MiscellaneousUtils.cs
│ │ │ ├── NullableAttributes.cs
│ │ │ ├── ReflectionDelegateFactory.cs
│ │ │ ├── ReflectionObject.cs
│ │ │ ├── ReflectionUtils.cs
│ │ │ ├── RequiresDynamicCodeAttribute.cs
│ │ │ ├── RequiresUnreferencedCodeAttribute.cs
│ │ │ ├── StringBuffer.cs
│ │ │ ├── StringReference.cs
│ │ │ ├── StringUtils.cs
│ │ │ ├── StructMultiKey.cs
│ │ │ ├── ThreadSafeStore.cs
│ │ │ ├── TypeExtensions.cs
│ │ │ ├── UnconditionalSuppressMessageAttribute.cs
│ │ │ └── ValidationUtils.cs
│ │ └── WriteState.cs
│ ├── Newtonsoft.Json.FuzzTests/
│ │ ├── FuzzTests.cs
│ │ └── Newtonsoft.Json.FuzzTests.csproj
│ ├── Newtonsoft.Json.TestConsole/
│ │ ├── App.config
│ │ ├── Newtonsoft.Json.TestConsole.csproj
│ │ └── Program.cs
│ ├── Newtonsoft.Json.Tests/
│ │ ├── App.config
│ │ ├── Benchmarks/
│ │ │ ├── BenchmarkConstants.cs
│ │ │ ├── DeserializeBenchmarks.cs
│ │ │ ├── DeserializeComparisonBenchmarks.cs
│ │ │ ├── JTokenBenchmarks.cs
│ │ │ ├── JValueConvertBenchmarks.cs
│ │ │ ├── JsonTextReaderBenchmarks.cs
│ │ │ ├── JsonTextWriterBenchmarks.cs
│ │ │ ├── LargeJArrayBenchmarks.cs
│ │ │ ├── LowLevelBenchmarks.cs
│ │ │ ├── Runner.cs
│ │ │ ├── SerializeBenchmarks.cs
│ │ │ ├── SerializeComparisonBenchmarks.cs
│ │ │ └── XmlNodeConverterBenchmarks.cs
│ │ ├── Bson/
│ │ │ ├── BsonReaderAsyncTests.cs
│ │ │ ├── BsonReaderTests.cs
│ │ │ ├── BsonWriterAsyncTests.cs
│ │ │ └── BsonWriterTests.cs
│ │ ├── Converters/
│ │ │ ├── BinaryConverterTests.cs
│ │ │ ├── CustomCreationConverterTests.cs
│ │ │ ├── DataSetConverterTests.cs
│ │ │ ├── DataTableConverterTests.cs
│ │ │ ├── DiscriminatedUnionConverterTests.cs
│ │ │ ├── ExpandoObjectConverterTests.cs
│ │ │ ├── GenericJsonConverterTests.cs
│ │ │ ├── IsoDateTimeConverterTests.cs
│ │ │ ├── JavaScriptDateTimeConverterTests.cs
│ │ │ ├── KeyValuePairConverterTests.cs
│ │ │ ├── ObjectIdConverterTests.cs
│ │ │ ├── RegexConverterTests.cs
│ │ │ ├── StringEnumConverterTests.cs
│ │ │ ├── UnixDateTimeConverterTests.cs
│ │ │ ├── VersionConverterTests.cs
│ │ │ └── XmlNodeConverterTest.cs
│ │ ├── DemoTests.cs
│ │ ├── Documentation/
│ │ │ ├── ConditionalPropertiesTests.cs
│ │ │ ├── ConvertingJsonAndXmlTests.cs
│ │ │ ├── JsonSchemaTests.cs
│ │ │ ├── LinqToJsonTests.cs
│ │ │ ├── PerformanceTests.cs
│ │ │ ├── ReadingAndWritingJsonTests.cs
│ │ │ ├── Samples/
│ │ │ │ ├── Bson/
│ │ │ │ │ ├── DeserializeFromBson.cs
│ │ │ │ │ ├── DeserializeFromBsonCollection.cs
│ │ │ │ │ └── SerializeToBson.cs
│ │ │ │ ├── Json/
│ │ │ │ │ ├── CustomJsonReader.cs
│ │ │ │ │ ├── CustomJsonWriter.cs
│ │ │ │ │ ├── ReadJsonWithJsonTextReader.cs
│ │ │ │ │ ├── ReadMultipleContentWithJsonReader.cs
│ │ │ │ │ └── WriteJsonWithJsonTextWriter.cs
│ │ │ │ ├── JsonPath/
│ │ │ │ │ ├── ErrorWhenNoMatchQuery.cs
│ │ │ │ │ ├── QueryJsonSelectToken.cs
│ │ │ │ │ ├── QueryJsonSelectTokenEscaped.cs
│ │ │ │ │ ├── QueryJsonSelectTokenJsonPath.cs
│ │ │ │ │ ├── QueryJsonSelectTokenWithLinq.cs
│ │ │ │ │ ├── RegexQuery.cs
│ │ │ │ │ └── StrictEqualsQuery.cs
│ │ │ │ ├── Linq/
│ │ │ │ │ ├── Clone.cs
│ │ │ │ │ ├── CreateJsonAnonymousObject.cs
│ │ │ │ │ ├── CreateJsonCollectionInitializer.cs
│ │ │ │ │ ├── CreateJsonDeclaratively.cs
│ │ │ │ │ ├── CreateJsonDynamic.cs
│ │ │ │ │ ├── CreateJsonJTokenWriter.cs
│ │ │ │ │ ├── CreateJsonManually.cs
│ │ │ │ │ ├── CreateReader.cs
│ │ │ │ │ ├── CreateWriter.cs
│ │ │ │ │ ├── DeepEquals.cs
│ │ │ │ │ ├── DeserializeWithLinq.cs
│ │ │ │ │ ├── FromObject.cs
│ │ │ │ │ ├── JObjectProperties.cs
│ │ │ │ │ ├── JTokenAnnotation.cs
│ │ │ │ │ ├── JValueCast.cs
│ │ │ │ │ ├── JValueValue.cs
│ │ │ │ │ ├── MergeJson.cs
│ │ │ │ │ ├── ModifyJson.cs
│ │ │ │ │ ├── ParseJsonAny.cs
│ │ │ │ │ ├── ParseJsonArray.cs
│ │ │ │ │ ├── ParseJsonObject.cs
│ │ │ │ │ ├── QueryJson.cs
│ │ │ │ │ ├── QueryJsonDynamic.cs
│ │ │ │ │ ├── QueryJsonIgnoreCase.cs
│ │ │ │ │ ├── QueryJsonLinq.cs
│ │ │ │ │ ├── ReadJTokenFromBson.cs
│ │ │ │ │ ├── ReadJson.cs
│ │ │ │ │ ├── SerializeWithLinq.cs
│ │ │ │ │ ├── ToObjectComplex.cs
│ │ │ │ │ ├── ToObjectGeneric.cs
│ │ │ │ │ ├── ToObjectType.cs
│ │ │ │ │ ├── ToString.cs
│ │ │ │ │ ├── ToStringJsonConverter.cs
│ │ │ │ │ ├── WriteJTokenToBson.cs
│ │ │ │ │ └── WriteToJsonFile.cs
│ │ │ │ ├── Schema/
│ │ │ │ │ ├── CreateJsonSchemaManually.cs
│ │ │ │ │ ├── JTokenIsValid.cs
│ │ │ │ │ ├── JTokenIsValidWithMessages.cs
│ │ │ │ │ ├── JTokenValidateWithEvent.cs
│ │ │ │ │ ├── JsonSchemaParse.cs
│ │ │ │ │ ├── JsonValidatingReaderAndSerializer.cs
│ │ │ │ │ ├── LoadJsonSchemaFromFile.cs
│ │ │ │ │ ├── RefJsonSchemaResolver.cs
│ │ │ │ │ └── SaveJsonSchemaToFile.cs
│ │ │ │ ├── Serializer/
│ │ │ │ │ ├── CustomContractResolver.cs
│ │ │ │ │ ├── CustomJsonConverter.cs
│ │ │ │ │ ├── CustomJsonConverterGeneric.cs
│ │ │ │ │ ├── CustomTraceWriter.cs
│ │ │ │ │ ├── DataContractAndDataMember.cs
│ │ │ │ │ ├── DefaultSettings.cs
│ │ │ │ │ ├── DefaultValueAttributeIgnore.cs
│ │ │ │ │ ├── DefaultValueHandlingIgnore.cs
│ │ │ │ │ ├── DeserializeAnonymousType.cs
│ │ │ │ │ ├── DeserializeCollection.cs
│ │ │ │ │ ├── DeserializeConstructorHandling.cs
│ │ │ │ │ ├── DeserializeCustomCreationConverter.cs
│ │ │ │ │ ├── DeserializeDataSet.cs
│ │ │ │ │ ├── DeserializeDateFormatString.cs
│ │ │ │ │ ├── DeserializeDictionary.cs
│ │ │ │ │ ├── DeserializeExtensionData.cs
│ │ │ │ │ ├── DeserializeImmutableCollections.cs
│ │ │ │ │ ├── DeserializeMetadataPropertyHandling.cs
│ │ │ │ │ ├── DeserializeMissingMemberHandling.cs
│ │ │ │ │ ├── DeserializeObject.cs
│ │ │ │ │ ├── DeserializeObjectCreationHandling.cs
│ │ │ │ │ ├── DeserializeWithDependencyInjection.cs
│ │ │ │ │ ├── DeserializeWithJsonSerializerFromFile.cs
│ │ │ │ │ ├── ErrorHandlingAttribute.cs
│ │ │ │ │ ├── ErrorHandlingEvent.cs
│ │ │ │ │ ├── JsonConstructorAttribute.cs
│ │ │ │ │ ├── JsonConverterAttributeClass.cs
│ │ │ │ │ ├── JsonConverterAttributeProperty.cs
│ │ │ │ │ ├── JsonObjectAttributeOptIn.cs
│ │ │ │ │ ├── JsonObjectAttributeOverrideIEnumerable.cs
│ │ │ │ │ ├── JsonPropertyItemLevelSetting.cs
│ │ │ │ │ ├── JsonPropertyName.cs
│ │ │ │ │ ├── JsonPropertyOrder.cs
│ │ │ │ │ ├── JsonPropertyPropertyLevelSetting.cs
│ │ │ │ │ ├── JsonPropertyRequired.cs
│ │ │ │ │ ├── MaxDepth.cs
│ │ │ │ │ ├── NamingStrategyAttributes.cs
│ │ │ │ │ ├── NamingStrategyCamelCase.cs
│ │ │ │ │ ├── NamingStrategyKebabCase.cs
│ │ │ │ │ ├── NamingStrategySkipDictionaryKeys.cs
│ │ │ │ │ ├── NamingStrategySkipSpecifiedNames.cs
│ │ │ │ │ ├── NamingStrategySnakeCase.cs
│ │ │ │ │ ├── NullValueHandlingIgnore.cs
│ │ │ │ │ ├── PopulateObject.cs
│ │ │ │ │ ├── PreserveReferencesHandlingObject.cs
│ │ │ │ │ ├── PropertyJsonIgnore.cs
│ │ │ │ │ ├── ReferenceLoopHandlingIgnore.cs
│ │ │ │ │ ├── SerializationCallbackAttributes.cs
│ │ │ │ │ ├── SerializeCollection.cs
│ │ │ │ │ ├── SerializeConditionalProperty.cs
│ │ │ │ │ ├── SerializeContractResolver.cs
│ │ │ │ │ ├── SerializeDataSet.cs
│ │ │ │ │ ├── SerializeDateFormatHandling.cs
│ │ │ │ │ ├── SerializeDateFormatString.cs
│ │ │ │ │ ├── SerializeDateTimeZoneHandling.cs
│ │ │ │ │ ├── SerializeDictionary.cs
│ │ │ │ │ ├── SerializeExtensionData.cs
│ │ │ │ │ ├── SerializeImmutableCollections.cs
│ │ │ │ │ ├── SerializeObject.cs
│ │ │ │ │ ├── SerializeRawJson.cs
│ │ │ │ │ ├── SerializeSerializationBinder.cs
│ │ │ │ │ ├── SerializeTypeNameHandling.cs
│ │ │ │ │ ├── SerializeUnindentedJson.cs
│ │ │ │ │ ├── SerializeWithJsonConverters.cs
│ │ │ │ │ ├── SerializeWithJsonSerializerToFile.cs
│ │ │ │ │ └── TraceWriter.cs
│ │ │ │ └── Xml/
│ │ │ │ ├── ConvertJsonToXml.cs
│ │ │ │ ├── ConvertXmlToJson.cs
│ │ │ │ └── ConvertXmlToJsonForceArray.cs
│ │ │ ├── SerializationTests.cs
│ │ │ └── TraceWriterTests.cs
│ │ ├── ExceptionTests.cs
│ │ ├── FileSystemEntityModel.Designer.cs
│ │ ├── FileSystemEntityModel.edmx
│ │ ├── FuzzRegressionTests.cs
│ │ ├── Issues/
│ │ │ ├── Issue0198.cs
│ │ │ ├── Issue0573.cs
│ │ │ ├── Issue1307.cs
│ │ │ ├── Issue1321.cs
│ │ │ ├── Issue1322.cs
│ │ │ ├── Issue1327.cs
│ │ │ ├── Issue1351.cs
│ │ │ ├── Issue1353.cs
│ │ │ ├── Issue1362.cs
│ │ │ ├── Issue1396.cs
│ │ │ ├── Issue1404.cs
│ │ │ ├── Issue1445.cs
│ │ │ ├── Issue1460.cs
│ │ │ ├── Issue1461.cs
│ │ │ ├── Issue1512.cs
│ │ │ ├── Issue1541.cs
│ │ │ ├── Issue1545.cs
│ │ │ ├── Issue1552.cs
│ │ │ ├── Issue1561.cs
│ │ │ ├── Issue1566.cs
│ │ │ ├── Issue1569.cs
│ │ │ ├── Issue1574.cs
│ │ │ ├── Issue1576.cs
│ │ │ ├── Issue1592.cs
│ │ │ ├── Issue1593.cs
│ │ │ ├── Issue1597.cs
│ │ │ ├── Issue1598.cs
│ │ │ ├── Issue1619.cs
│ │ │ ├── Issue1620.cs
│ │ │ ├── Issue1642.cs
│ │ │ ├── Issue1682.cs
│ │ │ ├── Issue1708.cs
│ │ │ ├── Issue1711.cs
│ │ │ ├── Issue1719.cs
│ │ │ ├── Issue1725.cs
│ │ │ ├── Issue1734.cs
│ │ │ ├── Issue1752.cs
│ │ │ ├── Issue1757.cs
│ │ │ ├── Issue1778.cs
│ │ │ ├── Issue1796.cs
│ │ │ ├── Issue1798.cs
│ │ │ ├── Issue1834.cs
│ │ │ ├── Issue1837.cs
│ │ │ ├── Issue1874.cs
│ │ │ ├── Issue1877.cs
│ │ │ ├── Issue1962.cs
│ │ │ ├── Issue1984.cs
│ │ │ ├── Issue2082.cs
│ │ │ ├── Issue2156.cs
│ │ │ ├── Issue2165.cs
│ │ │ ├── Issue2176.cs
│ │ │ ├── Issue2444.cs
│ │ │ ├── Issue2450.cs
│ │ │ ├── Issue2484.cs
│ │ │ ├── Issue2492.cs
│ │ │ ├── Issue2504.cs
│ │ │ ├── Issue2529.cs
│ │ │ ├── Issue2638.cs
│ │ │ ├── Issue2694.cs
│ │ │ ├── Issue2708.cs
│ │ │ ├── Issue2735.cs
│ │ │ ├── Issue2768.cs
│ │ │ ├── Issue2775.cs
│ │ │ ├── Issue3055.cs
│ │ │ ├── Issue3056.cs
│ │ │ └── Issue3080.cs
│ │ ├── JsonArrayAttributeTests.cs
│ │ ├── JsonConvertTest.cs
│ │ ├── JsonTextReaderTests/
│ │ │ ├── ExceptionHandlingAsyncTests.cs
│ │ │ ├── ExceptionHandlingTests.cs
│ │ │ ├── FloatAsyncTests.cs
│ │ │ ├── FloatTests.cs
│ │ │ ├── MiscAsyncTests.cs
│ │ │ ├── MiscTests.cs
│ │ │ ├── ParseAsyncTests.cs
│ │ │ ├── ParseTests.cs
│ │ │ ├── ReadAsyncTests.cs
│ │ │ └── ReadTests.cs
│ │ ├── JsonTextWriterAsyncTests.cs
│ │ ├── JsonTextWriterTest.cs
│ │ ├── JsonValidatingReaderTests.cs
│ │ ├── Linq/
│ │ │ ├── AnnotationsTests.cs
│ │ │ ├── ComponentModel/
│ │ │ │ ├── BindingTests.cs
│ │ │ │ └── JPropertyDescriptorTests.cs
│ │ │ ├── DynamicTests.cs
│ │ │ ├── JArrayTests.cs
│ │ │ ├── JConstructorAsyncTests.cs
│ │ │ ├── JConstructorTests.cs
│ │ │ ├── JObjectAsyncTests.cs
│ │ │ ├── JObjectTests.cs
│ │ │ ├── JPropertyAsyncTests.cs
│ │ │ ├── JPropertyTests.cs
│ │ │ ├── JRawTests.cs
│ │ │ ├── JTokenAsyncTests.cs
│ │ │ ├── JTokenEqualityComparerTests.cs
│ │ │ ├── JTokenReaderAsyncTests.cs
│ │ │ ├── JTokenReaderTest.cs
│ │ │ ├── JTokenTests.cs
│ │ │ ├── JTokenWriterAsyncTests.cs
│ │ │ ├── JTokenWriterTest.cs
│ │ │ ├── JValueAsyncTests.cs
│ │ │ ├── JValueTests.cs
│ │ │ ├── JsonPath/
│ │ │ │ ├── JPathExecuteTests.cs
│ │ │ │ ├── JPathParseTests.cs
│ │ │ │ └── QueryExpressionTests.cs
│ │ │ ├── LinqToJsonAsyncTests.cs
│ │ │ ├── LinqToJsonTest.cs
│ │ │ └── MergeTests.cs
│ │ ├── LinqToSql/
│ │ │ ├── Department.cs
│ │ │ ├── DepartmentConverter.cs
│ │ │ ├── GuidByteArrayConverter.cs
│ │ │ ├── LinqToSqlClasses.dbml
│ │ │ ├── LinqToSqlClasses.dbml.layout
│ │ │ ├── LinqToSqlClasses.designer.cs
│ │ │ ├── LinqToSqlClassesSerializationTests.cs
│ │ │ ├── Person.cs
│ │ │ └── Role.cs
│ │ ├── Newtonsoft.Json.Tests.csproj
│ │ ├── PoisonText.txt
│ │ ├── Properties/
│ │ │ └── AssemblyInfo.cs
│ │ ├── Schema/
│ │ │ ├── ExtensionsTests.cs
│ │ │ ├── JsonSchemaBuilderTests.cs
│ │ │ ├── JsonSchemaGeneratorTests.cs
│ │ │ ├── JsonSchemaModelBuilderTests.cs
│ │ │ ├── JsonSchemaNodeTests.cs
│ │ │ ├── JsonSchemaSpecTests.cs
│ │ │ ├── JsonSchemaTests.cs
│ │ │ ├── PerformanceTests.cs
│ │ │ └── Specs/
│ │ │ ├── additionalItems.json
│ │ │ ├── additionalProperties.json
│ │ │ ├── dependencies.json
│ │ │ ├── disallow.json
│ │ │ ├── divisibleBy.json
│ │ │ ├── enum.json
│ │ │ ├── extends.json
│ │ │ ├── items.json
│ │ │ ├── maxItems.json
│ │ │ ├── maxLength.json
│ │ │ ├── maximum.json
│ │ │ ├── minItems.json
│ │ │ ├── minLength.json
│ │ │ ├── minimum.json
│ │ │ ├── pattern.json
│ │ │ ├── patternProperties.json
│ │ │ ├── properties.json
│ │ │ ├── ref.json
│ │ │ ├── required.json
│ │ │ ├── type.json
│ │ │ └── uniqueItems.json
│ │ ├── Serialization/
│ │ │ ├── CamelCaseNamingStrategyTests.cs
│ │ │ ├── CamelCasePropertyNamesContractResolverTests.cs
│ │ │ ├── ConstructorHandlingTests.cs
│ │ │ ├── ContractResolverTests.cs
│ │ │ ├── DateOnlyTests.cs
│ │ │ ├── DateTimeZoneHandlingTests.cs
│ │ │ ├── DefaultValueHandlingTests.cs
│ │ │ ├── DependencyInjectionTests.cs
│ │ │ ├── DynamicConcreteTests.cs
│ │ │ ├── DynamicTests.cs
│ │ │ ├── EntitiesSerializationTests.cs
│ │ │ ├── ExtensionDataTests.cs
│ │ │ ├── FSharpTests.cs
│ │ │ ├── ImmutableCollectionsTests.cs
│ │ │ ├── JsonPropertyCollectionTests.cs
│ │ │ ├── JsonSerializerCollectionsTests.cs
│ │ │ ├── JsonSerializerTest.cs
│ │ │ ├── KebabCaseNamingStrategyTests.cs
│ │ │ ├── MetadataPropertyHandlingTests.cs
│ │ │ ├── MissingMemberHandlingTests.cs
│ │ │ ├── NamingStrategyEquality.cs
│ │ │ ├── NullValueHandlingTests.cs
│ │ │ ├── PopulateTests.cs
│ │ │ ├── PreserveReferencesHandlingTests.cs
│ │ │ ├── ReferenceLoopHandlingTests.cs
│ │ │ ├── ReflectionAttributeProviderTests.cs
│ │ │ ├── SerializationErrorHandlingTests.cs
│ │ │ ├── SerializationEventAttributeTests.cs
│ │ │ ├── ShouldSerializeTests.cs
│ │ │ ├── SnakeCaseNamingStrategyTests.cs
│ │ │ ├── TimeOnlyTests.cs
│ │ │ ├── TraceWriterTests.cs
│ │ │ ├── TypeNameHandlingTests.cs
│ │ │ └── WebApiIntegrationTests.cs
│ │ ├── SpaceShipV2.bson
│ │ ├── TestFixtureBase.cs
│ │ ├── TestObjects/
│ │ │ ├── A.cs
│ │ │ ├── AATestClass.cs
│ │ │ ├── Aa.cs
│ │ │ ├── AbstractDictionaryTestClass.cs
│ │ │ ├── AbstractGenericBase.cs
│ │ │ ├── AbstractImplementationDictionaryTestClass.cs
│ │ │ ├── AbstractImplementationListTestClass.cs
│ │ │ ├── AbstractImplementationTestClass.cs
│ │ │ ├── AbstractListTestClass.cs
│ │ │ ├── AbstractTestClass.cs
│ │ │ ├── Address.cs
│ │ │ ├── Animal.cs
│ │ │ ├── AnswerFilterModel.cs
│ │ │ ├── Antworten.cs
│ │ │ ├── ArgumentConverterPrecedenceClassConverter.cs
│ │ │ ├── Article.cs
│ │ │ ├── ArticleCollection.cs
│ │ │ ├── AttachmentReadConverter.cs
│ │ │ ├── B.cs
│ │ │ ├── BBTestClass.cs
│ │ │ ├── BadJsonPropertyClass.cs
│ │ │ ├── Bar.cs
│ │ │ ├── Bar1.cs
│ │ │ ├── BaseClass.cs
│ │ │ ├── BaseClassVirtual.cs
│ │ │ ├── BaseClassWithProtectedVirtual.cs
│ │ │ ├── BaseConstructorType.cs
│ │ │ ├── BaseDataContract.cs
│ │ │ ├── BaseDataContractWithHidden.cs
│ │ │ ├── BaseType.cs
│ │ │ ├── BaseWithContract.cs
│ │ │ ├── BaseWithPrivate.cs
│ │ │ ├── BaseWithoutContract.cs
│ │ │ ├── Bb.cs
│ │ │ ├── Binding.cs
│ │ │ ├── Binding_DisallowNull.cs
│ │ │ ├── BusRun.cs
│ │ │ ├── ByteArrayTestClass.cs
│ │ │ ├── Car.cs
│ │ │ ├── ChildClass.cs
│ │ │ ├── ChildClassVirtual.cs
│ │ │ ├── ChildClassWithProtectedOverridePlusJsonProperty.cs
│ │ │ ├── ChildDataContractWithHidden.cs
│ │ │ ├── CircularConstructor1.cs
│ │ │ ├── CircularConstructor2.cs
│ │ │ ├── CircularReferenceClass.cs
│ │ │ ├── CircularReferenceWithIdClass.cs
│ │ │ ├── ClassAndMemberConverterClass.cs
│ │ │ ├── ClassAttributeBase.cs
│ │ │ ├── ClassAttributeDerived.cs
│ │ │ ├── ClassConverterPrecedenceClassConverter.cs
│ │ │ ├── ClassWithArray.cs
│ │ │ ├── ClassWithException.cs
│ │ │ ├── ClassWithGuid.cs
│ │ │ ├── ClassWithImplicitOperator.cs
│ │ │ ├── ClassWithTimeSpan.cs
│ │ │ ├── ClientMap.cs
│ │ │ ├── CollectionClassAttributeDerived.cs
│ │ │ ├── CommentTestClass.cs
│ │ │ ├── CommentTestObject.cs
│ │ │ ├── CompletionDataRequest.cs
│ │ │ ├── ComplexItem.cs
│ │ │ ├── Component.cs
│ │ │ ├── Computer.cs
│ │ │ ├── ConsoleWriter.cs
│ │ │ ├── ConstantTestClass.cs
│ │ │ ├── ConstructorAndDefaultValueAttributeTestClass.cs
│ │ │ ├── ConstructorAndRequiredTestClass.cs
│ │ │ ├── ConstructorCaseSensitivityClass.cs
│ │ │ ├── ConstructorCompexIgnoredProperty.cs
│ │ │ ├── ConstructorReadonlyFields.cs
│ │ │ ├── Container.cs
│ │ │ ├── Content.cs
│ │ │ ├── ContentBaseClass.cs
│ │ │ ├── ContentSubClass.cs
│ │ │ ├── ConverableMembers.cs
│ │ │ ├── ConvertableIntTestClass.cs
│ │ │ ├── ConverterPrecedenceClass.cs
│ │ │ ├── ConverterPrecedenceClassConverter.cs
│ │ │ ├── ConvertibleId.cs
│ │ │ ├── ConvertibleInt.cs
│ │ │ ├── CustomerDataSet.cs
│ │ │ ├── CustomerWithMetadataType.cs
│ │ │ ├── DTOWithParameterisedConstructor.cs
│ │ │ ├── DTOWithoutParameterisedConstructor.cs
│ │ │ ├── DataContractJsonSerializerTestClass.cs
│ │ │ ├── DataContractPrivateMembers.cs
│ │ │ ├── DataContractSerializationAttributesClass.cs
│ │ │ ├── DateTimeErrorObjectCollection.cs
│ │ │ ├── DateTimeOffsetTestClass.cs
│ │ │ ├── DateTimeOffsetWrapper.cs
│ │ │ ├── DateTimeTestClass.cs
│ │ │ ├── DateTimeWrapper.cs
│ │ │ ├── DecimalTest.cs
│ │ │ ├── DecimalTestClass.cs
│ │ │ ├── DefaultValueAttributeTestClass.cs
│ │ │ ├── DerivedConstructorType.cs
│ │ │ ├── DerivedEvent.cs
│ │ │ ├── DerivedSerializationEventTestObject.cs
│ │ │ ├── DerivedType.cs
│ │ │ ├── DerivedWithPrivate.cs
│ │ │ ├── DeserializeStringConvert.cs
│ │ │ ├── DictionaryInterfaceClass.cs
│ │ │ ├── DictionaryKey.cs
│ │ │ ├── DictionaryKeyCast.cs
│ │ │ ├── DictionaryKeyContractResolver.cs
│ │ │ ├── DictionaryWithNoDefaultConstructor.cs
│ │ │ ├── DictionaryWithNoNull.cs
│ │ │ ├── DirectoryAccount.cs
│ │ │ ├── DoubleClass.cs
│ │ │ ├── EmployeeReference.cs
│ │ │ ├── EmptyJsonValueTestClass.cs
│ │ │ ├── EncodingReadConverter.cs
│ │ │ ├── EnumA.cs
│ │ │ ├── EnumerableArrayPropertyClass.cs
│ │ │ ├── EnumerableClass.cs
│ │ │ ├── ErroringClass.cs
│ │ │ ├── ErroringJsonConverter.cs
│ │ │ ├── ErroringTestClass.cs
│ │ │ ├── Events/
│ │ │ │ ├── Event.cs
│ │ │ │ ├── Event1.cs
│ │ │ │ └── EventType.cs
│ │ │ ├── ExistingValueClass.cs
│ │ │ ├── FaqItem.cs
│ │ │ ├── Foo.cs
│ │ │ ├── Foo1.cs
│ │ │ ├── Foo64.cs
│ │ │ ├── FooBar1.cs
│ │ │ ├── FooConstructor.cs
│ │ │ ├── FooRequired.cs
│ │ │ ├── Friend.cs
│ │ │ ├── GameObject.cs
│ │ │ ├── GenericIEnumerableWithImplicitConversion.cs
│ │ │ ├── GenericImpl.cs
│ │ │ ├── GenericListAndDictionaryInterfaceProperties.cs
│ │ │ ├── GeoCoding/
│ │ │ │ ├── AddressDetails.cs
│ │ │ │ ├── AdministrativeArea.cs
│ │ │ │ ├── Country.cs
│ │ │ │ ├── GoogleMapGeocoderStructure.cs
│ │ │ │ ├── Locality.cs
│ │ │ │ ├── Placemark.cs
│ │ │ │ ├── Point.cs
│ │ │ │ ├── PostalCode.cs
│ │ │ │ ├── Status.cs
│ │ │ │ ├── SubAdministrativeArea.cs
│ │ │ │ └── Thoroughfare.cs
│ │ │ ├── GeometricForms/
│ │ │ │ ├── Shape.cs
│ │ │ │ └── Tags.cs
│ │ │ ├── GetOnlyPropertyClass.cs
│ │ │ ├── HasByteArray.cs
│ │ │ ├── HolderClass.cs
│ │ │ ├── Human.cs
│ │ │ ├── IInterfaceObject.cs
│ │ │ ├── IKeyValueId.cs
│ │ │ ├── IMainClass.cs
│ │ │ ├── IMyInterface.cs
│ │ │ ├── IPrivateImplementationA.cs
│ │ │ ├── IPrivateImplementationB.cs
│ │ │ ├── IPrivateOverriddenImplementation.cs
│ │ │ ├── ISerializableTestObject.cs
│ │ │ ├── ISerializableWithoutAttributeTestObject.cs
│ │ │ ├── ISubclass.cs
│ │ │ ├── ISubclassBase.cs
│ │ │ ├── IdReferenceResolver.cs
│ │ │ ├── IgnoreDataMemberTestClass.cs
│ │ │ ├── IgnoredPropertiesContractResolver.cs
│ │ │ ├── IgnoredPropertiesTestClass.cs
│ │ │ ├── IgnoredProperty.cs
│ │ │ ├── ImmutableStruct.cs
│ │ │ ├── ImplementInterfaceObject.cs
│ │ │ ├── IncompatibleJsonAttributeClass.cs
│ │ │ ├── IncompleteTestClass.cs
│ │ │ ├── IntToFloatConverter.cs
│ │ │ ├── InterfacePropertyTestClass.cs
│ │ │ ├── Invoice.cs
│ │ │ ├── Item.cs
│ │ │ ├── ItemBase.cs
│ │ │ ├── ItemConverterTestClass.cs
│ │ │ ├── ItemConverterTestConverter.cs
│ │ │ ├── JRawValueTestObject.cs
│ │ │ ├── JTokenTestClass.cs
│ │ │ ├── JaggedArray.cs
│ │ │ ├── JsonIgnoreAttributeOnClassTestClass.cs
│ │ │ ├── JsonIgnoreAttributeTestClass.cs
│ │ │ ├── JsonPropertyClass.cs
│ │ │ ├── JsonPropertyConverterContractResolver.cs
│ │ │ ├── JsonPropertyConverterTestClass.cs
│ │ │ ├── JsonPropertyWithHandlingValues.cs
│ │ │ ├── JsonReaderStubWithIsClosed.cs
│ │ │ ├── JsonTextReaderTests/
│ │ │ │ ├── FakeArrayPool.cs
│ │ │ │ ├── SlowStream.cs
│ │ │ │ ├── ToggleReaderError.cs
│ │ │ │ └── UnmanagedResourceFakingJsonReader.cs
│ │ │ ├── KVPair.cs
│ │ │ ├── KeyValueId.cs
│ │ │ ├── KeyValueTestClass.cs
│ │ │ ├── Link.cs
│ │ │ ├── ListErrorObject.cs
│ │ │ ├── ListErrorObjectCollection.cs
│ │ │ ├── ListOfIds.cs
│ │ │ ├── ListSourceTest.cs
│ │ │ ├── ListTestClass.cs
│ │ │ ├── LogEntry.cs
│ │ │ ├── LogEvent.cs
│ │ │ ├── MailAddressReadConverter.cs
│ │ │ ├── MainClass.cs
│ │ │ ├── MemberConverterClass.cs
│ │ │ ├── MemberConverterPrecedenceClassConverter.cs
│ │ │ ├── MessageWithIsoDate.cs
│ │ │ ├── MethodExecutorObject.cs
│ │ │ ├── MetroColorConverter.cs
│ │ │ ├── MetroPropertyNameResolver.cs
│ │ │ ├── MetroStringConverter.cs
│ │ │ ├── ModelStateDictionary.cs
│ │ │ ├── Money/
│ │ │ │ ├── Currency.cs
│ │ │ │ └── Tags.cs
│ │ │ ├── Movie.cs
│ │ │ ├── MovieWithJsonObjectNullValueHandlingIgnore.cs
│ │ │ ├── MovieWithJsonObjectNullValueHandlingInclude.cs
│ │ │ ├── MultiIndexBase.cs
│ │ │ ├── MultiIndexSuper.cs
│ │ │ ├── MultipleItemsClass.cs
│ │ │ ├── MultipleParametrizedConstructorsJsonConstructor.cs
│ │ │ ├── MyClass.cs
│ │ │ ├── MyEnum.cs
│ │ │ ├── MyFactory.cs
│ │ │ ├── MyInterfaceConverter.cs
│ │ │ ├── MyObservableObject.cs
│ │ │ ├── MyTuple.cs
│ │ │ ├── MyTuplePartial.cs
│ │ │ ├── Name.cs
│ │ │ ├── NameContainer.cs
│ │ │ ├── NameContainerConverter.cs
│ │ │ ├── NoConstructorReadOnlyCollection.cs
│ │ │ ├── NoConstructorReadOnlyDictionary.cs
│ │ │ ├── NonDefaultConstructorWithReadOnlyCollectionProperty.cs
│ │ │ ├── NonDefaultConstructorWithReadOnlyDictionaryProperty.cs
│ │ │ ├── NonPublicConstructorWithJsonConstructor.cs
│ │ │ ├── NonRequest.cs
│ │ │ ├── NullTestClass.cs
│ │ │ ├── NullableDateTimeTestClass.cs
│ │ │ ├── NullableFloats.cs
│ │ │ ├── NullableGuid.cs
│ │ │ ├── NullableGuidCountingJsonTextWriter.cs
│ │ │ ├── NullableLongTestClass.cs
│ │ │ ├── NullableStructPropertyClass.cs
│ │ │ ├── NullableTestClass.cs
│ │ │ ├── ObjectArrayPropertyTest.cs
│ │ │ ├── ObservableObject.cs
│ │ │ ├── OptInClass.cs
│ │ │ ├── Organization/
│ │ │ │ ├── Employee.cs
│ │ │ │ ├── IPerson.cs
│ │ │ │ ├── Manager.cs
│ │ │ │ ├── Person.cs
│ │ │ │ ├── PersonPropertyClass.cs
│ │ │ │ └── WagePerson.cs
│ │ │ ├── Pair.cs
│ │ │ ├── ParticipantEntity.cs
│ │ │ ├── PersonConverter.cs
│ │ │ ├── PersonError.cs
│ │ │ ├── PersonRaw.cs
│ │ │ ├── PersonReference.cs
│ │ │ ├── PersonSerializable.cs
│ │ │ ├── PersonWithPrivateConstructor.cs
│ │ │ ├── PhoneNumber.cs
│ │ │ ├── PocoDataContractSerializationAttributesClass.cs
│ │ │ ├── Pos.cs
│ │ │ ├── PosConverter.cs
│ │ │ ├── PosDouble.cs
│ │ │ ├── PosDoubleConverter.cs
│ │ │ ├── PreserveReferencesCallbackTestObject.cs
│ │ │ ├── PrivateConstructorTestClass.cs
│ │ │ ├── PrivateConstructorWithPublicParameterizedConstructorTestClass.cs
│ │ │ ├── PrivateImplementationAClass.cs
│ │ │ ├── PrivateImplementationBClass.cs
│ │ │ ├── PrivateMembersClass.cs
│ │ │ ├── PrivateMembersClassWithAttributes.cs
│ │ │ ├── PrivateSetterBase.cs
│ │ │ ├── PrivateSetterDerived.cs
│ │ │ ├── Product.cs
│ │ │ ├── ProductCollection.cs
│ │ │ ├── ProductShort.cs
│ │ │ ├── PropertyCase.cs
│ │ │ ├── PropertyItemConverter.cs
│ │ │ ├── PublicConstructorOverridenByJsonConstructor.cs
│ │ │ ├── PublicParameterizedConstructorRequiringConverterTestClass.cs
│ │ │ ├── PublicParameterizedConstructorRequiringConverterWithParameterAttributeTestClass.cs
│ │ │ ├── PublicParameterizedConstructorRequiringConverterWithPropertyAttributeTestClass.cs
│ │ │ ├── PublicParameterizedConstructorTestClass.cs
│ │ │ ├── PublicParameterizedConstructorWithNonPropertyParameterTestClass.cs
│ │ │ ├── PublicParameterizedConstructorWithPropertyNameConflict.cs
│ │ │ ├── PublicParameterizedConstructorWithPropertyNameConflictWithAttribute.cs
│ │ │ ├── Ratio.cs
│ │ │ ├── ReflectionContractResolver.cs
│ │ │ ├── RequestOnly.cs
│ │ │ ├── RequiredMembersClass.cs
│ │ │ ├── RequiredObject.cs
│ │ │ ├── RequiredPropertyConstructorTestClass.cs
│ │ │ ├── RequiredPropertyTestClass.cs
│ │ │ ├── ResponseWithNewGenericProperty.cs
│ │ │ ├── ResponseWithNewGenericPropertyOverride.cs
│ │ │ ├── ResponseWithNewGenericPropertyVirtual.cs
│ │ │ ├── RoleTransfer.cs
│ │ │ ├── RoleTransferDirection.cs
│ │ │ ├── RoleTransferOperation.cs
│ │ │ ├── RootObject.cs
│ │ │ ├── SearchResult.cs
│ │ │ ├── SelectListItem.cs
│ │ │ ├── SerializableContractResolver.cs
│ │ │ ├── SerializationEventTestDictionary.cs
│ │ │ ├── SerializationEventTestList.cs
│ │ │ ├── SerializationEventTestObject.cs
│ │ │ ├── SerializationEventTestObjectWithConstructor.cs
│ │ │ ├── SetOnlyPropertyClass.cs
│ │ │ ├── SetOnlyPropertyClass2.cs
│ │ │ ├── Shortie.cs
│ │ │ ├── SimpleResponse.cs
│ │ │ ├── SqlTypesDataSet.Designer.cs
│ │ │ ├── SqlTypesDataSet.xsc
│ │ │ ├── SqlTypesDataSet.xsd
│ │ │ ├── SqlTypesDataSet.xss
│ │ │ ├── StaticTestClass.cs
│ │ │ ├── Store.cs
│ │ │ ├── StoreColor.cs
│ │ │ ├── StringDictionaryTestClass.cs
│ │ │ ├── StructISerializable.cs
│ │ │ ├── StructTest.cs
│ │ │ ├── StructWithAttribute.cs
│ │ │ ├── SubKlass.cs
│ │ │ ├── SubWithContractNewProperties.cs
│ │ │ ├── SubWithContractVirtualProperties.cs
│ │ │ ├── SubWithoutContractNewProperties.cs
│ │ │ ├── SubWithoutContractVirtualProperties.cs
│ │ │ ├── Subclass.cs
│ │ │ ├── SuperKlass.cs
│ │ │ ├── Test.cs
│ │ │ ├── TestClass.cs
│ │ │ ├── TestClassConvertable.cs
│ │ │ ├── TestComponent.cs
│ │ │ ├── TestComponentSimple.cs
│ │ │ ├── TestObject.cs
│ │ │ ├── ThisGenericTest.cs
│ │ │ ├── TimeZoneOffsetObject.cs
│ │ │ ├── TraceWriter.cs
│ │ │ ├── TypeClass.cs
│ │ │ ├── TypeConverterJsonConverter.cs
│ │ │ ├── TypeConverterSize.cs
│ │ │ ├── TypeConverterSizeConverter.cs
│ │ │ ├── TypedSubHashtable.cs
│ │ │ ├── UriGuidTimeSpanTestClass.cs
│ │ │ ├── UserNullable.cs
│ │ │ ├── Vector.cs
│ │ │ ├── VectorParent.cs
│ │ │ ├── VersionKeyedCollection.cs
│ │ │ ├── VersionOld.cs
│ │ │ ├── VirtualOverrideNewBaseObject.cs
│ │ │ ├── VirtualOverrideNewChildObject.cs
│ │ │ ├── VirtualOverrideNewChildWithDifferentOverrideObject.cs
│ │ │ ├── Widget.cs
│ │ │ ├── Widget1.cs
│ │ │ ├── WidgetId.cs
│ │ │ ├── WidgetId1.cs
│ │ │ ├── WidgetIdJsonConverter.cs
│ │ │ ├── WithEnums.cs
│ │ │ ├── XNodeTestObject.cs
│ │ │ └── XmlNodeTestObject.cs
│ │ ├── Utilities/
│ │ │ ├── ConvertUtilsTests.cs
│ │ │ ├── DateTimeUtilsTests.cs
│ │ │ ├── DynamicReflectionDelegateFactoryTests.cs
│ │ │ ├── EnumUtilsTests.cs
│ │ │ ├── ExpressionReflectionDelegateFactoryTests.cs
│ │ │ ├── LateboundReflectionDelegateFactoryTests.cs
│ │ │ ├── ReflectionUtilsTests.cs
│ │ │ └── StringUtilsTests.cs
│ │ ├── large.json
│ │ └── large_sample.xml
│ ├── Newtonsoft.Json.slnx
│ ├── NuGet.Config
│ └── global.json
└── azure-pipelines.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.jpg binary
*.png binary
*.gif binary
*.bson binary
*.cs text diff=csharp
*.vb text
*.c text
*.cpp text
*.cxx text
*.h text
*.hxx text
*.py text
*.rb text
*.java text
*.html text
*.htm text
*.css text
*.scss text
*.sass text
*.less text
*.js text
*.lisp text
*.clj text
*.sql text
*.php text
*.lua text
*.m text
*.asm text
*.erl text
*.fs text
*.fsx text
*.hs text
*.ps1 text
*.psm1 text
*.csproj text merge=union
*.vbproj text merge=union
*.fsproj text merge=union
*.dbproj text merge=union
*.sln text eol=crlf merge=union
================================================
FILE: .github/workflows/codeql.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL Advanced"
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: '42 20 * * 6'
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: csharp
build-mode: autobuild
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Add any setup steps before running the `github/codeql-action/init` action.
# This includes steps like installing compilers or runtimes (`actions/setup-node`
# or others). This is typically only required for manual builds.
# - name: Setup runtime (example)
# uses: actions/setup-example@v1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
================================================
FILE: .gitignore
================================================
[Bb]in/
[Oo]bj/
[Ww]orking*/
Build/Temp/
Doc/doc.shfbproj_*
TestResults/
AppPackages/
BenchmarkDotNet.Artifacts/
*.suo
*.user
*.userprefs
_ReSharper.*
*.ReSharper.user
*.resharper.user
.vs/
.vscode/
*.lock.json
*.nuget.props
*.nuget.targets
*.orig
.DS_Store
================================================
FILE: Build/Sign-Package.ps1
================================================
$currentDirectory = split-path $MyInvocation.MyCommand.Definition
# See if we have the SignKeyVaultCertificate available
if ([string]::IsNullOrEmpty($Env:SignKeyVaultCertificate)){
Write-Host "Key vault detail not found, not signing packages"
return;
}
dotnet tool install --tool-path . --prerelease sign
$files = gci $Env:ArtifactDirectory\*.nupkg,*.zip -recurse | Select -ExpandProperty FullName
$signKeyVaultCertificate = $Env:SignKeyVaultCertificate
$signKeyVaultUrl = $Env:SignKeyVaultUrl
foreach ($file in $files){
Write-Host "Submitting $file for signing"
.\sign code azure-key-vault $file `
--publisher-name "Newtonsoft" `
--description "Json.NET" `
--description-url "https://www.newtonsoft.com/json" `
--azure-key-vault-certificate $signKeyVaultCertificate `
--azure-key-vault-url $signKeyVaultUrl
Write-Host "Finished signing $file"
}
Write-Host "Sign-package complete"
================================================
FILE: Build/appsettings.json
================================================
{
"SignClient": {
"AzureAd": {
"AADInstance": "https://login.microsoftonline.com/",
"ClientId": "c248d68a-ba6f-4aa9-8a68-71fe872063f8",
"TenantId": "16076fdc-fcc1-4a15-b1ca-32c9a255900e"
},
"Service": {
"Url": "https://codesign.dotnetfoundation.org/",
"ResourceId": "https://SignService/3c30251f-36f3-490b-a955-520addb85001"
}
}
}
================================================
FILE: Build/build.ps1
================================================
properties {
$zipFileName = "Json130r5.zip"
$majorVersion = "13.0"
$majorWithReleaseVersion = "13.0.5"
$nugetPrerelease = $null
$version = GetVersion $majorWithReleaseVersion
$packageId = "Newtonsoft.Json"
$signAssemblies = $false
$signKeyPath = "C:\Development\Releases\newtonsoft.snk"
$buildDocumentation = $false
$buildNuGet = $true
$msbuildVerbosity = 'minimal'
$treatWarningsAsErrors = $false
$workingName = if ($workingName) {$workingName} else {"Working"}
$assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'}
$netCliChannel = "STS"
$netCliVersion = "9.0.300"
$nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$ensureNetCliSdk = $true
$baseDir = resolve-path ..
$buildDir = "$baseDir\Build"
$sourceDir = "$baseDir\Src"
$docDir = "$baseDir\Doc"
$releaseDir = "$baseDir\Release"
$workingDir = "$baseDir\$workingName"
$nugetPath = "$buildDir\Temp\nuget.exe"
$vswhereVersion = "3.1.7"
$vswherePath = "$buildDir\Temp\vswhere.$vswhereVersion"
$nunitConsoleVersion = "3.8.0"
$nunitConsolePath = "$buildDir\Temp\NUnit.ConsoleRunner.$nunitConsoleVersion"
$builds = @(
@{Framework = "net6.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true},
@{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net5.0"; Enabled=$true},
@{Framework = "netstandard1.3"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp3.1"; Enabled=$true},
@{Framework = "netstandard1.0"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp2.1"; Enabled=$true},
@{Framework = "net45"; TestsFunction = "NUnitTests"; TestFramework = "net46"; NUnitFramework="net-4.0"; Enabled=$true},
@{Framework = "net40"; TestsFunction = "NUnitTests"; NUnitFramework="net-4.0"; Enabled=$true},
@{Framework = "net35"; TestsFunction = "NUnitTests"; NUnitFramework="net-2.0"; Enabled=$true},
@{Framework = "net20"; TestsFunction = "NUnitTests"; NUnitFramework="net-2.0"; Enabled=$true}
)
}
framework '4.6x86'
task default -depends Test,Package
# Ensure a clean working directory
task Clean {
Write-Host "Setting location to $baseDir"
Set-Location $baseDir
if (Test-Path -path $workingDir)
{
Write-Host "Deleting existing working directory $workingDir"
Execute-Command -command { del $workingDir -Recurse -Force }
}
Write-Host "Creating working directory $workingDir"
New-Item -Path $workingDir -ItemType Directory
}
# Build each solution, optionally signed
task Build -depends Clean {
$script:enabledBuilds = $builds | ? {$_.Enabled}
Write-Host -ForegroundColor Green "Found $($script:enabledBuilds.Length) enabled builds"
mkdir "$buildDir\Temp" -Force
if ($ensureNetCliSdk)
{
EnsureDotNetCli
}
EnsureNuGetExists
EnsureNuGetPackage "vswhere" $vswherePath $vswhereVersion
EnsureNuGetPackage "NUnit.ConsoleRunner" $nunitConsolePath $nunitConsoleVersion
$script:msBuildPath = GetMsBuildPath
Write-Host "MSBuild path $script:msBuildPath"
NetCliBuild
}
# Optional build documentation, add files to final zip
task Package -depends Build {
foreach ($build in $script:enabledBuilds)
{
$finalDir = $build.Framework
$sourcePath = "$sourceDir\Newtonsoft.Json\bin\Release\$finalDir"
if (!(Test-Path -path $sourcePath))
{
throw "Could not find $sourcePath"
}
robocopy $sourcePath $workingDir\Package\Bin\$finalDir *.dll *.pdb *.xml /NFL /NDL /NJS /NC /NS /NP /XO /XF *.CodeAnalysisLog.xml | Out-Default
}
if ($buildNuGet)
{
Write-Host -ForegroundColor Green "Copy NuGet package"
mkdir $workingDir\NuGet
move -Path $sourceDir\Newtonsoft.Json\bin\Release\*.nupkg -Destination $workingDir\NuGet
move -Path $sourceDir\Newtonsoft.Json\bin\Release\*.snupkg -Destination $workingDir\NuGet
}
Write-Host "Build documentation: $buildDocumentation"
if ($buildDocumentation)
{
$mainBuild = $script:enabledBuilds | where { $_.Framework -eq "net45" } | select -first 1
$mainBuildFinalDir = $mainBuild.Framework
$documentationSourcePath = "$workingDir\Package\Bin\$mainBuildFinalDir"
$docOutputPath = "$workingDir\Documentation\"
Write-Host -ForegroundColor Green "Building documentation from $documentationSourcePath"
Write-Host "Documentation output to $docOutputPath"
# Sandcastle has issues when compiling with .NET 4 MSBuild
exec { & $script:msBuildPath "/t:Clean;Rebuild" "/v:$msbuildVerbosity" "/p:Configuration=Release" "/p:DocumentationSourcePath=$documentationSourcePath" "/p:OutputPath=$docOutputPath" "/m" "$docDir\doc.shfbproj" | Out-Default } "Error building documentation. Check that you have Sandcastle, Sandcastle Help File Builder and HTML Help Workshop installed."
move -Path $workingDir\Documentation\LastBuild.log -Destination $workingDir\Documentation.log
}
Copy-Item -Path $docDir\readme.txt -Destination $workingDir\Package\
Copy-Item -Path $docDir\license.txt -Destination $workingDir\Package\
robocopy $sourceDir $workingDir\Package\Source\Src /MIR /NFL /NDL /NJS /NC /NS /NP /XD bin obj TestResults AppPackages .vs artifacts /XF *.suo *.user *.lock.json | Out-Default
robocopy $buildDir $workingDir\Package\Source\Build /MIR /NFL /NDL /NJS /NC /NS /NP /XD Temp /XF runbuild.txt | Out-Default
robocopy $docDir $workingDir\Package\Source\Doc /MIR /NFL /NDL /NJS /NC /NS /NP | Out-Default
# include fuzz tests in ADO pipeline artifacts
mkdir $workingDir\FuzzTests
Copy-Item -Path $sourceDir\Newtonsoft.Json.FuzzTests\bin\Release\net6.0\* -Destination $workingDir\FuzzTests
Compress-Archive -Path $workingDir\Package\* -DestinationPath $workingDir\$zipFileName
}
task Test -depends Build {
foreach ($build in $script:enabledBuilds)
{
Write-Host "Calling $($build.TestsFunction)"
& $build.TestsFunction $build
}
}
function NetCliBuild()
{
$projectPath = "$sourceDir\Newtonsoft.Json.slnx"
$libraryFrameworks = ($script:enabledBuilds | Select-Object @{Name="Framework";Expression={$_.Framework}} | select -expand Framework) -join ";"
$testFrameworks = ($script:enabledBuilds | Select-Object @{Name="Resolved";Expression={if ($_.TestFramework -ne $null) { $_.TestFramework } else { $_.Framework }}} | select -expand Resolved) -join ";"
$additionalConstants = switch($signAssemblies) { $true { "SIGNED" } default { "" } }
Write-Host -ForegroundColor Green "Restoring packages for $libraryFrameworks in $projectPath"
Write-Host
exec { & $script:msBuildPath "/t:restore" "/v:$msbuildVerbosity" "/p:Configuration=Release" "/p:LibraryFrameworks=`"$libraryFrameworks`"" "/p:TestFrameworks=`"$testFrameworks`"" "/m" $projectPath | Out-Default } "Error restoring $projectPath"
Write-Host -ForegroundColor Green "Building $libraryFrameworks $assemblyVersion in $projectPath"
Write-Host
exec { & $script:msBuildPath "/t:build" "/v:$msbuildVerbosity" $projectPath "/p:Configuration=Release" "/p:LibraryFrameworks=`"$libraryFrameworks`"" "/p:TestFrameworks=`"$testFrameworks`"" "/p:AssemblyOriginatorKeyFile=$signKeyPath" "/p:SignAssembly=$signAssemblies" "/p:TreatWarningsAsErrors=$treatWarningsAsErrors" "/p:AdditionalConstants=$additionalConstants" "/p:GeneratePackageOnBuild=$buildNuGet" "/p:ContinuousIntegrationBuild=true" "/p:PackageId=$packageId" "/p:VersionPrefix=$majorWithReleaseVersion" "/p:VersionSuffix=$nugetPrerelease" "/p:AssemblyVersion=$assemblyVersion" "/p:FileVersion=$version" "/m" }
}
function EnsureDotnetCli()
{
Write-Host "Downloading dotnet-install.ps1"
# https://stackoverflow.com/questions/36265534/invoke-webrequest-ssl-fails
[Net.ServicePointManager]::SecurityProtocol = 'TLS12'
Invoke-WebRequest `
-Uri "https://dot.net/v1/dotnet-install.ps1" `
-OutFile "$buildDir\Temp\dotnet-install.ps1"
exec { & $buildDir\Temp\dotnet-install.ps1 -Channel $netCliChannel -Version $netCliVersion | Out-Default }
exec { & $buildDir\Temp\dotnet-install.ps1 -Channel $netCliChannel -Version '6.0.400' | Out-Default }
exec { & $buildDir\Temp\dotnet-install.ps1 -Channel $netCliChannel -Version '3.1.402' | Out-Default }
exec { & $buildDir\Temp\dotnet-install.ps1 -Channel $netCliChannel -Version '2.1.818' | Out-Default }
}
function EnsureNuGetExists()
{
if (!(Test-Path $nugetPath))
{
Write-Host "Couldn't find nuget.exe. Downloading from $nugetUrl to $nugetPath"
(New-Object System.Net.WebClient).DownloadFile($nugetUrl, $nugetPath)
}
}
function EnsureNuGetPackage($packageName, $packagePath, $packageVersion)
{
if (!(Test-Path $packagePath))
{
Write-Host "Couldn't find $packagePath. Downloading with NuGet"
exec { & $nugetPath install $packageName -OutputDirectory $buildDir\Temp -Version $packageVersion -ConfigFile "$sourceDir\nuget.config" | Out-Default } "Error restoring $packagePath"
}
}
function GetMsBuildPath()
{
$path = & $vswherePath\tools\vswhere.exe -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
if (!($path))
{
throw "Could not find Visual Studio install path"
}
$msBuildPath = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
if (Test-Path $msBuildPath)
{
return $msBuildPath
}
$msBuildPath = join-path $path 'MSBuild\Current\Bin\MSBuild.exe'
if (Test-Path $msBuildPath)
{
return $msBuildPath
}
throw "Could not find MSBuild path"
}
function NetCliTests($build)
{
$projectPath = "$sourceDir\Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj"
$location = "$sourceDir\Newtonsoft.Json.Tests"
$testDir = if ($build.TestFramework -ne $null) { $build.TestFramework } else { $build.Framework }
try
{
Set-Location $location
exec { dotnet --version | Out-Default }
Write-Host -ForegroundColor Green "Running tests for $testDir"
Write-Host "Location: $location"
Write-Host "Project path: $projectPath"
Write-Host
exec { dotnet test $projectPath -f $testDir -c Release -l trx --results-directory $workingDir --no-restore --no-build | Out-Default }
}
finally
{
Set-Location $baseDir
}
}
function NUnitTests($build)
{
$testDir = if ($build.TestFramework -ne $null) { $build.TestFramework } else { $build.Framework }
$framework = $build.NUnitFramework
$testRunDir = "$sourceDir\Newtonsoft.Json.Tests\bin\Release\$testDir"
Write-Host -ForegroundColor Green "Running NUnit tests $testDir"
Write-Host
try
{
Set-Location $testRunDir
exec { & $nunitConsolePath\tools\nunit3-console.exe "$testRunDir\Newtonsoft.Json.Tests.dll" --framework=$framework --result=$workingDir\$testDir.xml --out=$workingDir\$testDir.txt | Out-Default } "Error running $testDir tests"
}
finally
{
Set-Location $baseDir
}
}
function GetVersion($majorVersion)
{
$now = [DateTime]::Now
$year = $now.Year - 2000
$month = $now.Month
$totalMonthsSince2000 = ($year * 12) + $month
$day = $now.Day
$minor = "{0}{1:00}" -f $totalMonthsSince2000, $day
$hour = $now.Hour
$minute = $now.Minute
$revision = "{0:00}{1:00}" -f $hour, $minute
return $majorVersion + "." + $minor
}
function Edit-XmlNodes {
param (
[xml] $doc,
[string] $xpath = $(throw "xpath is a required parameter"),
[string] $value = $(throw "value is a required parameter")
)
$nodes = $doc.SelectNodes($xpath)
$count = $nodes.Count
Write-Host "Found $count nodes with path '$xpath'"
foreach ($node in $nodes) {
if ($node -ne $null) {
if ($node.NodeType -eq "Element")
{
$node.InnerXml = $value
}
else
{
$node.Value = $value
}
}
}
}
function Execute-Command($command) {
$currentRetry = 0
$success = $false
do {
try
{
& $command
$success = $true
}
catch [System.Exception]
{
if ($currentRetry -gt 5) {
throw $_.Exception.ToString()
} else {
write-host "Retry $currentRetry"
Start-Sleep -s 1
}
$currentRetry = $currentRetry + 1
}
} while (!$success)
}
================================================
FILE: Build/localbuild.ps1
================================================
Start-Transcript ($PSScriptRoot + '\Temp\runbuild.txt')
$version = Get-Content "$PSScriptRoot\version.json" | Out-String | ConvertFrom-Json
& $PSScriptRoot\runbuild.ps1 -properties @{"majorVersion"="$($version.Major).0"; "majorWithReleaseVersion"="$($version.Major).0.$($version.Release)"; "nugetPrerelease"=$version.Prerelease; "zipFileName"="Json$($version.Major)0r$($version.Release).zip"; "treatWarningsAsErrors"=$true}
================================================
FILE: Build/psake.psm1
================================================
# psake
# Copyright (c) 2012 James Kovacs
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#Requires -Version 2.0
#-- Public Module Functions --#
# .ExternalHelp psake.psm1-help.xml
function Invoke-Task
{
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)] [string]$taskName
)
Assert $taskName ($msgs.error_invalid_task_name)
$taskKey = $taskName.ToLower()
if ($currentContext.aliases.Contains($taskKey)) {
$taskName = $currentContext.aliases.$taskKey.Name
$taskKey = $taskName.ToLower()
}
$currentContext = $psake.context.Peek()
Assert ($currentContext.tasks.Contains($taskKey)) ($msgs.error_task_name_does_not_exist -f $taskName)
if ($currentContext.executedTasks.Contains($taskKey)) { return }
Assert (!$currentContext.callStack.Contains($taskKey)) ($msgs.error_circular_reference -f $taskName)
$currentContext.callStack.Push($taskKey)
$task = $currentContext.tasks.$taskKey
$precondition_is_valid = & $task.Precondition
if (!$precondition_is_valid) {
WriteColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan
} else {
if ($taskKey -ne 'default') {
if ($task.PreAction -or $task.PostAction) {
Assert ($task.Action -ne $null) ($msgs.error_missing_action_parameter -f $taskName)
}
if ($task.Action) {
try {
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$currentContext.currentTaskName = $taskName
& $currentContext.taskSetupScriptBlock
if ($task.PreAction) {
& $task.PreAction
}
if ($currentContext.config.taskNameFormat -is [ScriptBlock]) {
& $currentContext.config.taskNameFormat $taskName
} else {
WriteColoredOutput ($currentContext.config.taskNameFormat -f $taskName) -foregroundcolor Cyan
}
foreach ($variable in $task.requiredVariables) {
Assert ((test-path "variable:$variable") -and ((get-variable $variable).Value -ne $null)) ($msgs.required_variable_not_set -f $variable, $taskName)
}
& $task.Action
if ($task.PostAction) {
& $task.PostAction
}
& $currentContext.taskTearDownScriptBlock
$task.Duration = $stopwatch.Elapsed
} catch {
if ($task.ContinueOnError) {
"-"*70
WriteColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow
"-"*70
$task.Duration = $stopwatch.Elapsed
} else {
throw $_
}
}
} else {
# no action was specified but we still execute all the dependencies
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
}
} else {
foreach($childTask in $task.DependsOn) {
Invoke-Task $childTask
}
}
Assert (& $task.Postcondition) ($msgs.postcondition_failed -f $taskName)
}
$poppedTaskKey = $currentContext.callStack.Pop()
Assert ($poppedTaskKey -eq $taskKey) ($msgs.error_corrupt_callstack -f $taskKey,$poppedTaskKey)
$currentContext.executedTasks.Push($taskKey)
}
# .ExternalHelp psake.psm1-help.xml
function Exec
{
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][scriptblock]$cmd,
[Parameter(Position=1,Mandatory=0)][string]$errorMessage = ($msgs.error_bad_command -f $cmd),
[Parameter(Position=2,Mandatory=0)][int]$maxRetries = 0,
[Parameter(Position=3,Mandatory=0)][string]$retryTriggerErrorPattern = $null
)
$tryCount = 1
do {
try {
$global:lastexitcode = 0
& $cmd
if ($lastexitcode -ne 0) {
throw ("Exec: " + $errorMessage)
}
break
}
catch [Exception]
{
if ($tryCount -gt $maxRetries) {
throw $_
}
if ($retryTriggerErrorPattern -ne $null) {
$isMatch = [regex]::IsMatch($_.Exception.Message, $retryTriggerErrorPattern)
if ($isMatch -eq $false) {
throw $_
}
}
Write-Host "Try $tryCount failed, retrying again in 1 second..."
$tryCount++
[System.Threading.Thread]::Sleep([System.TimeSpan]::FromSeconds(1))
}
}
while ($true)
}
# .ExternalHelp psake.psm1-help.xml
function Assert
{
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)]$conditionToCheck,
[Parameter(Position=1,Mandatory=1)]$failureMessage
)
if (!$conditionToCheck) {
throw ("Assert: " + $failureMessage)
}
}
# .ExternalHelp psake.psm1-help.xml
function Task
{
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][string]$name = $null,
[Parameter(Position=1,Mandatory=0)][scriptblock]$action = $null,
[Parameter(Position=2,Mandatory=0)][scriptblock]$preaction = $null,
[Parameter(Position=3,Mandatory=0)][scriptblock]$postaction = $null,
[Parameter(Position=4,Mandatory=0)][scriptblock]$precondition = {$true},
[Parameter(Position=5,Mandatory=0)][scriptblock]$postcondition = {$true},
[Parameter(Position=6,Mandatory=0)][switch]$continueOnError = $false,
[Parameter(Position=7,Mandatory=0)][string[]]$depends = @(),
[Parameter(Position=8,Mandatory=0)][string[]]$requiredVariables = @(),
[Parameter(Position=9,Mandatory=0)][string]$description = $null,
[Parameter(Position=10,Mandatory=0)][string]$alias = $null,
[Parameter(Position=11,Mandatory=0)][string]$maxRetries = 0,
[Parameter(Position=12,Mandatory=0)][string]$retryTriggerErrorPattern = $null
)
if ($name -eq 'default') {
Assert (!$action) ($msgs.error_default_task_cannot_have_action)
}
$newTask = @{
Name = $name
DependsOn = $depends
PreAction = $preaction
Action = $action
PostAction = $postaction
Precondition = $precondition
Postcondition = $postcondition
ContinueOnError = $continueOnError
Description = $description
Duration = [System.TimeSpan]::Zero
RequiredVariables = $requiredVariables
Alias = $alias
MaxRetries = $maxRetries
RetryTriggerErrorPattern = $retryTriggerErrorPattern
}
$taskKey = $name.ToLower()
$currentContext = $psake.context.Peek()
Assert (!$currentContext.tasks.ContainsKey($taskKey)) ($msgs.error_duplicate_task_name -f $name)
$currentContext.tasks.$taskKey = $newTask
if($alias)
{
$aliasKey = $alias.ToLower()
Assert (!$currentContext.aliases.ContainsKey($aliasKey)) ($msgs.error_duplicate_alias_name -f $alias)
$currentContext.aliases.$aliasKey = $newTask
}
}
# .ExternalHelp psake.psm1-help.xml
function Properties {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][scriptblock]$properties
)
$psake.context.Peek().properties += $properties
}
# .ExternalHelp psake.psm1-help.xml
function Include {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][string]$fileNamePathToInclude
)
Assert (test-path $fileNamePathToInclude -pathType Leaf) ($msgs.error_invalid_include_path -f $fileNamePathToInclude)
$psake.context.Peek().includes.Enqueue((Resolve-Path $fileNamePathToInclude));
}
# .ExternalHelp psake.psm1-help.xml
function FormatTaskName {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)]$format
)
$psake.context.Peek().config.taskNameFormat = $format
}
# .ExternalHelp psake.psm1-help.xml
function TaskSetup {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][scriptblock]$setup
)
$psake.context.Peek().taskSetupScriptBlock = $setup
}
# .ExternalHelp psake.psm1-help.xml
function TaskTearDown {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][scriptblock]$teardown
)
$psake.context.Peek().taskTearDownScriptBlock = $teardown
}
# .ExternalHelp psake.psm1-help.xml
function Framework {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][string]$framework
)
$psake.context.Peek().config.framework = $framework
ConfigureBuildEnvironment
}
# .ExternalHelp psake.psm1-help.xml
function Invoke-psake {
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory = 0)][string] $buildFile,
[Parameter(Position = 1, Mandatory = 0)][string[]] $taskList = @(),
[Parameter(Position = 2, Mandatory = 0)][string] $framework,
[Parameter(Position = 3, Mandatory = 0)][switch] $docs = $false,
[Parameter(Position = 4, Mandatory = 0)][hashtable] $parameters = @{},
[Parameter(Position = 5, Mandatory = 0)][hashtable] $properties = @{},
[Parameter(Position = 6, Mandatory = 0)][alias("init")][scriptblock] $initialization = {},
[Parameter(Position = 7, Mandatory = 0)][switch] $nologo = $false,
[Parameter(Position = 8, Mandatory = 0)][switch] $detailedDocs = $false
)
try {
if (-not $nologo) {
"psake version {0}`nCopyright (c) 2010-2015 James Kovacs, Damian Hickey & Contributors`n" -f $psake.version
}
if (!$buildFile) {
$buildFile = $psake.config_default.buildFileName
}
elseif (!(test-path $buildFile -pathType Leaf) -and (test-path $psake.config_default.buildFileName -pathType Leaf)) {
# If the $config.buildFileName file exists and the given "buildfile" isn 't found assume that the given
# $buildFile is actually the target Tasks to execute in the $config.buildFileName script.
$taskList = $buildFile.Split(', ')
$buildFile = $psake.config_default.buildFileName
}
# Execute the build file to set up the tasks and defaults
Assert (test-path $buildFile -pathType Leaf) ($msgs.error_build_file_not_found -f $buildFile)
$psake.build_script_file = get-item $buildFile
$psake.build_script_dir = $psake.build_script_file.DirectoryName
$psake.build_success = $false
$psake.context.push(@{
"taskSetupScriptBlock" = {};
"taskTearDownScriptBlock" = {};
"executedTasks" = new-object System.Collections.Stack;
"callStack" = new-object System.Collections.Stack;
"originalEnvPath" = $env:path;
"originalDirectory" = get-location;
"originalErrorActionPreference" = $global:ErrorActionPreference;
"tasks" = @{};
"aliases" = @{};
"properties" = @();
"includes" = new-object System.Collections.Queue;
"config" = CreateConfigurationForNewContext $buildFile $framework
})
LoadConfiguration $psake.build_script_dir
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
set-location $psake.build_script_dir
LoadModules
$frameworkOldValue = $framework
. $psake.build_script_file.FullName
$currentContext = $psake.context.Peek()
if ($framework -ne $frameworkOldValue) {
writecoloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow
$currentContext.config.framework = $framework
}
ConfigureBuildEnvironment
while ($currentContext.includes.Count -gt 0) {
$includeFilename = $currentContext.includes.Dequeue()
. $includeFilename
}
if ($docs -or $detailedDocs) {
WriteDocumentation($detailedDocs)
CleanupEnvironment
return
}
foreach ($key in $parameters.keys) {
if (test-path "variable:\$key") {
set-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null
} else {
new-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null
}
}
# The initial dot (.) indicates that variables initialized/modified in the propertyBlock are available in the parent scope.
foreach ($propertyBlock in $currentContext.properties) {
. $propertyBlock
}
foreach ($key in $properties.keys) {
if (test-path "variable:\$key") {
set-item -path "variable:\$key" -value $properties.$key -WhatIf:$false -Confirm:$false | out-null
}
}
# Simple dot sourcing will not work. We have to force the script block into our
# module's scope in order to initialize variables properly.
. $MyInvocation.MyCommand.Module $initialization
# Execute the list of tasks or the default task
if ($taskList) {
foreach ($task in $taskList) {
invoke-task $task
}
} elseif ($currentContext.tasks.default) {
invoke-task default
} else {
throw $msgs.error_no_default_task
}
WriteColoredOutput ("`n" + $msgs.build_success + "`n") -foregroundcolor Green
WriteTaskTimeSummary $stopwatch.Elapsed
$psake.build_success = $true
} catch {
$currentConfig = GetCurrentConfigurationOrDefault
if ($currentConfig.verboseError) {
$error_message = "{0}: An Error Occurred. See Error Details Below: `n" -f (Get-Date)
$error_message += ("-" * 70) + "`n"
$error_message += "Error: {0}`n" -f (ResolveError $_ -Short)
$error_message += ("-" * 70) + "`n"
$error_message += ResolveError $_
$error_message += ("-" * 70) + "`n"
$error_message += "Script Variables" + "`n"
$error_message += ("-" * 70) + "`n"
$error_message += get-variable -scope script | format-table | out-string
} else {
# ($_ | Out-String) gets error messages with source information included.
$error_message = "Error: {0}: `n{1}" -f (Get-Date), (ResolveError $_ -Short)
}
$psake.build_success = $false
# if we are running in a nested scope (i.e. running a psake script from a psake script) then we need to re-throw the exception
# so that the parent script will fail otherwise the parent script will report a successful build
$inNestedScope = ($psake.context.count -gt 1)
if ( $inNestedScope ) {
throw $_
} else {
if (!$psake.run_by_psake_build_tester) {
WriteColoredOutput $error_message -foregroundcolor Red
}
}
} finally {
CleanupEnvironment
}
}
#-- Private Module Functions --#
function WriteColoredOutput {
param(
[string] $message,
[System.ConsoleColor] $foregroundcolor
)
$currentConfig = GetCurrentConfigurationOrDefault
if ($currentConfig.coloredOutput -eq $true) {
if (($Host.UI -ne $null) -and ($Host.UI.RawUI -ne $null) -and ($Host.UI.RawUI.ForegroundColor -ne $null)) {
$previousColor = $Host.UI.RawUI.ForegroundColor
$Host.UI.RawUI.ForegroundColor = $foregroundcolor
}
}
$message
if ($previousColor -ne $null) {
$Host.UI.RawUI.ForegroundColor = $previousColor
}
}
function LoadModules {
$currentConfig = $psake.context.peek().config
if ($currentConfig.modules) {
$scope = $currentConfig.moduleScope
$global = [string]::Equals($scope, "global", [StringComparison]::CurrentCultureIgnoreCase)
$currentConfig.modules | foreach {
resolve-path $_ | foreach {
"Loading module: $_"
$module = import-module $_ -passthru -DisableNameChecking -global:$global
if (!$module) {
throw ($msgs.error_loading_module -f $_.Name)
}
}
}
""
}
}
function LoadConfiguration {
param(
[string] $configdir = $PSScriptRoot
)
$psakeConfigFilePath = (join-path $configdir "psake-config.ps1")
if (test-path $psakeConfigFilePath -pathType Leaf) {
try {
$config = GetCurrentConfigurationOrDefault
. $psakeConfigFilePath
} catch {
throw "Error Loading Configuration from psake-config.ps1: " + $_
}
}
}
function GetCurrentConfigurationOrDefault() {
if ($psake.context.count -gt 0) {
return $psake.context.peek().config
} else {
return $psake.config_default
}
}
function CreateConfigurationForNewContext {
param(
[string] $buildFile,
[string] $framework
)
$previousConfig = GetCurrentConfigurationOrDefault
$config = new-object psobject -property @{
buildFileName = $previousConfig.buildFileName;
framework = $previousConfig.framework;
taskNameFormat = $previousConfig.taskNameFormat;
verboseError = $previousConfig.verboseError;
coloredOutput = $previousConfig.coloredOutput;
modules = $previousConfig.modules;
moduleScope = $previousConfig.moduleScope;
}
if ($framework) {
$config.framework = $framework;
}
if ($buildFile) {
$config.buildFileName = $buildFile;
}
return $config
}
function ConfigureBuildEnvironment {
$framework = $psake.context.peek().config.framework
if ($framework -cmatch '^((?:\d+\.\d+)(?:\.\d+){0,1})(x86|x64){0,1}$') {
$versionPart = $matches[1]
$bitnessPart = $matches[2]
} else {
throw ($msgs.error_invalid_framework -f $framework)
}
$versions = $null
$buildToolsVersions = $null
switch ($versionPart) {
'1.0' {
$versions = @('v1.0.3705')
}
'1.1' {
$versions = @('v1.1.4322')
}
'2.0' {
$versions = @('v2.0.50727')
}
'3.0' {
$versions = @('v2.0.50727')
}
'3.5' {
$versions = @('v3.5', 'v2.0.50727')
}
'4.0' {
$versions = @('v4.0.30319')
}
{($_ -eq '4.5.1') -or ($_ -eq '4.5.2')} {
$versions = @('v4.0.30319')
$buildToolsVersions = @('14.0', '12.0')
}
'4.6' {
$versions = @('v4.0.30319')
$buildToolsVersions = @('14.0')
}
default {
throw ($msgs.error_unknown_framework -f $versionPart, $framework)
}
}
$bitness = 'Framework'
if ($versionPart -ne '1.0' -and $versionPart -ne '1.1') {
switch ($bitnessPart) {
'x86' {
$bitness = 'Framework'
$buildToolsKey = 'MSBuildToolsPath32'
}
'x64' {
$bitness = 'Framework64'
$buildToolsKey = 'MSBuildToolsPath'
}
{ [string]::IsNullOrEmpty($_) } {
$ptrSize = [System.IntPtr]::Size
switch ($ptrSize) {
4 {
$bitness = 'Framework'
$buildToolsKey = 'MSBuildToolsPath32'
}
8 {
$bitness = 'Framework64'
$buildToolsKey = 'MSBuildToolsPath'
}
default {
throw ($msgs.error_unknown_pointersize -f $ptrSize)
}
}
}
default {
throw ($msgs.error_unknown_bitnesspart -f $bitnessPart, $framework)
}
}
}
$frameworkDirs = @()
if ($buildToolsVersions -ne $null) {
foreach($ver in $buildToolsVersions) {
if (Test-Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$ver") {
$frameworkDirs += (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$ver" -Name $buildToolsKey).$buildToolsKey
}
}
}
$frameworkDirs = $frameworkDirs + @($versions | foreach { "$env:windir\Microsoft.NET\$bitness\$_\" })
for ($i = 0; $i -lt $frameworkDirs.Count; $i++) {
$dir = $frameworkDirs[$i]
if ($dir -Match "\$\(Registry:HKEY_LOCAL_MACHINE(.*?)@(.*)\)") {
$key = "HKLM:" + $matches[1]
$name = $matches[2]
$dir = (Get-ItemProperty -Path $key -Name $name).$name
$frameworkDirs[$i] = $dir
}
}
$frameworkDirs | foreach { Assert (test-path $_ -pathType Container) ($msgs.error_no_framework_install_dir_found -f $_)}
$env:path = ($frameworkDirs -join ";") + ";$env:path"
# if any error occurs in a PS function then "stop" processing immediately
# this does not effect any external programs that return a non-zero exit code
$global:ErrorActionPreference = "Stop"
}
function CleanupEnvironment {
if ($psake.context.Count -gt 0) {
$currentContext = $psake.context.Peek()
$env:path = $currentContext.originalEnvPath
Set-Location $currentContext.originalDirectory
$global:ErrorActionPreference = $currentContext.originalErrorActionPreference
[void] $psake.context.Pop()
}
}
function SelectObjectWithDefault
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[PSObject]
$InputObject,
[string]
$Name,
$Value
)
process {
if ($_ -eq $null) { $Value }
elseif ($_ | Get-Member -Name $Name) {
$_.$Name
}
elseif (($_ -is [Hashtable]) -and ($_.Keys -contains $Name)) {
$_.$Name
}
else { $Value }
}
}
# borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx
# modified to better handle SQL errors
function ResolveError
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$ErrorRecord=$Error[0],
[Switch]
$Short
)
process {
if ($_ -eq $null) { $_ = $ErrorRecord }
$ex = $_.Exception
if (-not $Short) {
$error_message = "`nErrorRecord:{0}ErrorRecord.InvocationInfo:{1}Exception:`n{2}"
$formatted_errorRecord = $_ | format-list * -force | out-string
$formatted_invocationInfo = $_.InvocationInfo | format-list * -force | out-string
$formatted_exception = ''
$i = 0
while ($ex -ne $null) {
$i++
$formatted_exception += ("$i" * 70) + "`n" +
($ex | format-list * -force | out-string) + "`n"
$ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null
}
return $error_message -f $formatted_errorRecord, $formatted_invocationInfo, $formatted_exception
}
$lastException = @()
while ($ex -ne $null) {
$lastMessage = $ex | SelectObjectWithDefault -Name 'Message' -Value ''
$lastException += ($lastMessage -replace "`n", '')
if ($ex -is [Data.SqlClient.SqlException]) {
$lastException += "(Line [$($ex.LineNumber)] " +
"Procedure [$($ex.Procedure)] Class [$($ex.Class)] " +
" Number [$($ex.Number)] State [$($ex.State)] )"
}
$ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null
}
$shortException = $lastException -join ' --> '
$header = $null
$current = $_
$header = (($_.InvocationInfo |
SelectObjectWithDefault -Name 'PositionMessage' -Value '') -replace "`n", ' '),
($_ | SelectObjectWithDefault -Name 'Message' -Value ''),
($_ | SelectObjectWithDefault -Name 'Exception' -Value '') |
? { -not [String]::IsNullOrEmpty($_) } |
Select -First 1
$delimiter = ''
if ((-not [String]::IsNullOrEmpty($header)) -and
(-not [String]::IsNullOrEmpty($shortException)))
{ $delimiter = ' [<<==>>] ' }
return "$($header)$($delimiter)Exception: $($shortException)"
}
}
function WriteDocumentation($showDetailed) {
$currentContext = $psake.context.Peek()
if ($currentContext.tasks.default) {
$defaultTaskDependencies = $currentContext.tasks.default.DependsOn
} else {
$defaultTaskDependencies = @()
}
$docs = $currentContext.tasks.Keys | foreach-object {
if ($_ -eq "default") {
return
}
$task = $currentContext.tasks.$_
new-object PSObject -property @{
Name = $task.Name;
Alias = $task.Alias;
Description = $task.Description;
"Depends On" = $task.DependsOn -join ", "
Default = if ($defaultTaskDependencies -contains $task.Name) { $true }
}
}
if ($showDetailed) {
$docs | sort 'Name' | format-list -property Name,Alias,Description,"Depends On",Default
} else {
$docs | sort 'Name' | format-table -autoSize -wrap -property Name,Alias,"Depends On",Default,Description
}
}
function WriteTaskTimeSummary($invokePsakeDuration) {
if ($psake.context.count -gt 0) {
"-" * 70
"Build Time Report"
"-" * 70
$list = @()
$currentContext = $psake.context.Peek()
while ($currentContext.executedTasks.Count -gt 0) {
$taskKey = $currentContext.executedTasks.Pop()
$task = $currentContext.tasks.$taskKey
if ($taskKey -eq "default") {
continue
}
$list += new-object PSObject -property @{
Name = $task.Name;
Duration = $task.Duration
}
}
[Array]::Reverse($list)
$list += new-object PSObject -property @{
Name = "Total:";
Duration = $invokePsakeDuration
}
# using "out-string | where-object" to filter out the blank line that format-table prepends
$list | format-table -autoSize -property Name,Duration | out-string -stream | where-object { $_ }
}
}
DATA msgs {
convertfrom-stringdata @'
error_invalid_task_name = Task name should not be null or empty string.
error_task_name_does_not_exist = Task {0} does not exist.
error_circular_reference = Circular reference found for task {0}.
error_missing_action_parameter = Action parameter must be specified when using PreAction or PostAction parameters for task {0}.
error_corrupt_callstack = Call stack was corrupt. Expected {0}, but got {1}.
error_invalid_framework = Invalid .NET Framework version, {0} specified.
error_unknown_framework = Unknown .NET Framework version, {0} specified in {1}.
error_unknown_pointersize = Unknown pointer size ({0}) returned from System.IntPtr.
error_unknown_bitnesspart = Unknown .NET Framework bitness, {0}, specified in {1}.
error_no_framework_install_dir_found = No .NET Framework installation directory found at {0}.
error_bad_command = Error executing command {0}.
error_default_task_cannot_have_action = 'default' task cannot specify an action.
error_duplicate_task_name = Task {0} has already been defined.
error_duplicate_alias_name = Alias {0} has already been defined.
error_invalid_include_path = Unable to include {0}. File not found.
error_build_file_not_found = Could not find the build file {0}.
error_no_default_task = 'default' task required.
error_loading_module = Error loading module {0}.
warning_deprecated_framework_variable = Warning: Using global variable $framework to set .NET framework version used is deprecated. Instead use Framework function or configuration file psake-config.ps1.
required_variable_not_set = Variable {0} must be set to run task {1}.
postcondition_failed = Postcondition failed for task {0}.
precondition_was_false = Precondition was false, not executing task {0}.
continue_on_error = Error in task {0}. {1}
build_success = Build Succeeded!
'@
}
import-localizeddata -bindingvariable msgs -erroraction silentlycontinue
$script:psake = @{}
$psake.version = "4.4.2" # contains the current version of psake
$psake.context = new-object system.collections.stack # holds onto the current state of all variables
$psake.run_by_psake_build_tester = $false # indicates that build is being run by psake-BuildTester
$psake.config_default = new-object psobject -property @{
buildFileName = "default.ps1";
framework = "4.0";
taskNameFormat = "Executing {0}";
verboseError = $false;
coloredOutput = $true;
modules = $null;
moduleScope = "";
} # contains default configuration, can be overriden in psake-config.ps1 in directory with psake.psm1 or in directory with current build script
$psake.build_success = $false # indicates that the current build was successful
$psake.build_script_file = $null # contains a System.IO.FileInfo for the current build script
$psake.build_script_dir = "" # contains a string with fully-qualified path to current build script
LoadConfiguration
export-modulemember -function Invoke-psake, Invoke-Task, Task, Properties, Include, FormatTaskName, TaskSetup, TaskTearDown, Framework, Assert, Exec -variable psake
================================================
FILE: Build/runbuild.cmd
================================================
cls
powershell -Command "& { Start-Transcript '%~dp0\Temp\runbuild.txt'; Import-Module '%~dp0\psake.psm1'; Invoke-psake '%~dp0..\Build\build.ps1' %*; Stop-Transcript; exit !($psake.build_success); }"
ECHO %ERRORLEVEL%
EXIT /B %ERRORLEVEL%
================================================
FILE: Build/runbuild.ps1
================================================
param(
[hashtable] $parameters = @{},
[hashtable] $properties = @{}
)
$path = Split-Path -Path $MyInvocation.MyCommand.Path
write-host "Importing psake"
Import-Module ($path + '\psake.psm1')
Try
{
write-host "Starting build.ps1"
Invoke-psake ($path + '\build.ps1') -properties $properties -parameters $parameters
if ($psake.build_success -eq $false)
{
write-host "build.ps1 failed" -fore RED
exit 1
}
else
{
write-host "build.ps1 succeeded" -fore GREEN
exit 0
}
}
Finally
{
Remove-Module psake
}
================================================
FILE: Build/version.json
================================================
{
"Major": 13,
"Release": 5,
"Prerelease": "beta1",
"Assembly": null
}
================================================
FILE: CONTRIBUTING.md
================================================
# How to contribute
Please read these guidelines before contributing to Json.NET:
- [Question or Problem?](#question)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submitting a Pull Request](#pullrequest)
- [Contributor License Agreement](#cla)
## Got a Question or Problem?
If you have questions about how to use Json.NET, please read the
[Json.NET documentation][documentation] or ask on [Stack Overflow][stackoverflow]. There are
thousands of Json.NET questions on Stack Overflow with the [json.net][stackoverflow] tag.
GitHub issues are only for [reporting bugs](#issue) and [feature requests](#feature), not
questions or help.
## Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help by
submitting an issue to the [GitHub Repository][github]. Even better you can submit a Pull Request
with a fix.
When submitting an issue please include the following information:
- A description of the issue
- The JSON, classes, and Json.NET code related to the issue
- The exception message and stacktrace if an error was thrown
- If possible, please include code that reproduces the issue. [DropBox][dropbox] or GitHub's
[Gist][gist] can be used to share large code samples, or you could
[submit a pull request](#pullrequest) with the issue reproduced in a new test.
The more information you include about the issue, the more likely it is to be fixed!
## Want a Feature?
You can request a new feature by submitting an issue to the [GitHub Repository][github]. Before
requesting a feature consider the following:
- Json.NET has many extensibility points, it is possible you can implement your feature today without
modifying Json.NET
- Stability is important. Json.NET is used by thousands of other libraries and features that require
large breaking changes are unlikely to be accepted
## Submitting a Pull Request
When submitting a pull request to the [GitHub Repository][github] make sure to do the following:
- Check that new and updated code follows Json.NET's existing code formatting and naming standard
- Run Json.NET's unit tests to ensure no existing functionality has been affected
- Write new unit tests to test your changes. All features and fixed bugs must have tests to verify
they work
Read [GitHub Help][pullrequesthelp] for more details about creating pull requests.
## Contributor License Agreement
By contributing your code to Json.NET you grant James Newton-King a non-exclusive, irrevocable, worldwide,
royalty-free, sublicenseable, transferable license under all of Your relevant intellectual property rights
(including copyright, patent, and any other rights), to use, copy, prepare derivative works of, distribute and
publicly perform and display the Contributions on any licensing terms, including without limitation:
(a) open source licenses like the MIT license; and (b) binary, proprietary, or commercial licenses. Except for the
licenses granted herein, You reserve all right, title, and interest in and to the Contribution.
You confirm that you are able to grant us these rights. You represent that You are legally entitled to grant the
above license. If Your employer has rights to intellectual property that You create, You represent that You have
received permission to make the Contributions on behalf of that employer, or that Your employer has waived such
rights for the Contributions.
You represent that the Contributions are Your original works of authorship, and to Your knowledge, no other person
claims, or has the right to claim, any right in any invention or patent related to the Contributions. You also
represent that You are not legally obligated, whether by entering into an agreement or otherwise, in any way that
conflicts with the terms of this license.
James Newton-King acknowledges that, except as explicitly described in this Agreement, any Contribution which
you provide is on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS
FOR A PARTICULAR PURPOSE.
[github]: https://github.com/JamesNK/Newtonsoft.Json
[documentation]: https://www.newtonsoft.com/json/help
[stackoverflow]: https://stackoverflow.com/questions/tagged/json.net
[dropbox]: https://www.dropbox.com
[gist]: https://gist.github.com
[pullrequesthelp]: https://help.github.com/articles/using-pull-requests
================================================
FILE: Doc/ConditionalProperties.aml
================================================
Json.NET has the ability to conditionally serialize properties by placing a ShouldSerialize method on a class.
This functionality is similar to the XmlSerializer ShouldSerialize featurehttp://msdn.microsoft.com/en-us/library/53b8022e.aspx_blank.ShouldSerializeTo conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name
with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the
property will be serialized, if it returns false then the property will be skipped.IContractResolverShouldSerialize can also be set using an T:Newtonsoft.Json.Serialization.IContractResolver.
Conditionally serializing a property using an IContractResolver is useful if you don't want to place a ShouldSerialize method on a class
or you didn't declare the class and are unable to.T:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.Serialization.IContractResolverP:Newtonsoft.Json.Serialization.JsonProperty.ShouldSerialize
================================================
FILE: Doc/ContractResolver.aml
================================================
The T:Newtonsoft.Json.Serialization.IContractResolver
interface provides a way to customize how the
JsonSerializer serializes and deserializes .NET objects to JSON without placing attributes on your classes.
Anything that can be set on an object, collection, property, etc, using attributes or methods to control serialization
can also be set using an IContractResolver.For performance you should create a contract resolver once and reuse instances when possible. Resolving contracts is slow and implementations of T:Newtonsoft.Json.Serialization.IContractResolver typically cache contracts.DefaultContractResolverThe T:Newtonsoft.Json.Serialization.DefaultContractResolver
is the default resolver used by the
serializer. It provides many avenues of extensibility in the form of
virtual methods that can be overridden.CamelCasePropertyNamesContractResolverT:Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver
inherits from DefaultContractResolver and simply overrides the JSON
property name to be written in camelcasehttp://en.wikipedia.org/wiki/CamelCase_blank.Custom IContractResolver ExamplesThis example sets a T:Newtonsoft.Json.JsonConverter for a type
using an IContractResolver. Using a contract resolver here is useful because DateTime is not your own type and it is not possible to place a JsonConverterAttribute on it.This example sets up conditional serialization for a property using an IContractResolver. This is useful if you want to conditionally serialize a property but don't want to add additional methods to your type.T:Newtonsoft.Json.Serialization.IContractResolverT:Newtonsoft.Json.Serialization.DefaultContractResolverT:Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver
================================================
FILE: Doc/ConvertingJSONandXML.aml
================================================
Json.NET supports converting JSON to XML and vice versa using the
T:Newtonsoft.Json.Converters.XmlNodeConverter.Elements, attributes, text, comments, character data, processing instructions,
namespaces, and the XML declaration are all preserved when converting between the two. The
only caveat is that it is possible to lose the order of differently named nodes at the
same level when they are grouped together into an array.Conversion RulesElements remain unchanged.Attributes are prefixed with an @ and should be at the start of the object.Single child text nodes are a value directly against an element, otherwise they are accessed via #text.The XML declaration and processing instructions are prefixed with ?.Character data, comments, whitespace and significant whitespace nodes are accessed via
#cdata-section, #comment, #whitespace and #significant-whitespace respectively.Multiple nodes with the same name at the same level are grouped together into an array.Empty elements are null.If the XML created from JSON doesn't match what you want, then you will need to convert it manually.
The best approach to do this is to load your JSON into a LINQ to JSON object like JObject or JArray and then use LINQ to create
an XDocument. The opposite process, using LINQ with an XDocument to create a JObject or JArray, also works.
You can find out more about using LINQ to JSON with LINQ here.The version of Json.NET being used in your application will change what XML conversion methods are available.
SerializeXmlNode/DeserializeXmlNode are available when the framework supports XmlDocument;
SerializeXNode/DeserializeXNode are available when the framework supports XDocument.SerializeXmlNodeThe JsonConvert has two helper methods for converting between JSON and XML. The first is
Overload:Newtonsoft.Json.JsonConvert.SerializeXmlNode.
This method takes an XmlNode and serializes it to JSON text.Because multiple nodes with the same name at the same level are grouped together into an array,
the conversion process can produce different JSON depending on the number of nodes. For example, if some
XML for a user has a single <Role> node, then that role will be text against
a JSON "Role" property, but if the user has multiple <Role>
nodes, then the role values will be placed in a JSON array.To fix this situation a custom XML attribute can be added to force a JSON array to be created.DeserializeXmlNodeThe second helper method on JsonConvert is
Overload:Newtonsoft.Json.JsonConvert.DeserializeXmlNode.
This method takes JSON text and deserializes it into an XmlNode.Because valid XML must have one root element, the JSON passed to DeserializeXmlNode should
have one property in the root JSON object. If the root JSON object has multiple properties, then
the overload that also takes an element name should be used. A root element with that name will
be inserted into the deserialized XmlNode.T:Newtonsoft.Json.Converters.XmlNodeConverterT:Newtonsoft.Json.JsonConvert
================================================
FILE: Doc/CreatingLINQtoJSON.aml
================================================
As well as parsing JSON from existing JSON strings, LINQ to JSON objects can be created from scratch to create new JSON structures.Manually Creating JSONSetting values and creating objects and arrays one at a time gives you
total control, but it is more verbose than other options.Creating JSON with LINQDeclaratively creating JSON objects using LINQ is a fast way to create JSON from collections of values.Creating JSON from an objectThe last option is to create a JSON object from a non-JSON type using the
Overload:Newtonsoft.Json.Linq.JObject.FromObject
method. Internally, FromObject will use the JsonSerializer to serialize the object to LINQ to JSON objects instead of text.The example below shows creating a JSON object from an anonymous object, but any
.NET type can be used with FromObject to create JSON.Overload:Newtonsoft.Json.Linq.JObject.FromObject
================================================
FILE: Doc/CustomCreationConverter.aml
================================================
The T:Newtonsoft.Json.Converters.CustomCreationConverter`1
is a JsonConverter that provides a way
to customize how an object is created during JSON deserialization. Once
the object has been created it will then have values populated onto it by
the serializer.ExampleThis is an extremely simple example. A more complicated scenario
could involve an object factory or service locator that resolves the
object at runtime.T:Newtonsoft.Json.Converters.CustomCreationConverter`1
================================================
FILE: Doc/DatesInJSON.aml
================================================
DateTimes in JSON are hard.The problem comes from the JSON spechttp://www.ietf.org/rfc/rfc4627.txt_blank itself: there is no literal
syntax for dates in JSON. The spec has objects, arrays, strings, integers,
and floats, but it defines no standard for what a date looks like.Dates and Json.NETThe default format used by Json.NET is the ISO 8601 standardhttp://en.wikipedia.org/wiki/ISO_8601_blank: "2012-03-19T07:22Z".Prior to Json.NET 4.5 dates were written using the Microsoft
format: "\/Date(1198908717056)\/". If you want to use this format, or
you want to maintain compatibility with Microsoft JSON serializers or
older versions of Json.NET, then change the
T:Newtonsoft.Json.DateFormatHandling
setting to MicrosoftDateFormat.The T:Newtonsoft.Json.DateTimeZoneHandling setting can be
used to convert a DateTime's T:System.DateTimeKind when serializing. For example set
DateTimeZoneHandling to Utc to serialize all DateTimes as UTC dates. Note that this setting does not effect DateTimeOffsets.If your dates don't follow the ISO 8601 standard, then the DateFormatString setting can be used to customize the format of
date strings that are read and written using .NET's custom date and time format syntaxhttps://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx_blank.DateTime JsonConvertersWith no standard for dates in JSON, the number of possible
different formats when interoping with other systems is endless.
Fortunately Json.NET has a solution to deal with reading and writing
custom dates: JsonConverters. A JsonConverter is used to override how a
type is serialized.Simply pass the JsonConverter you wish to use to the Json.NET
serializer.JavaScriptDateTimeConverterThe JavaScriptDateTimeConverter class is one of the two DateTime
JsonConverters that come with Json.NET. This converter serializes a
DateTime as a JavaScript Date objecthttp://msdn.microsoft.com/en-us/library/cd9w2te4.aspx_blank: new Date(1234656000000)Technically this is invalid JSON according to the spec, but all
browsers and some JSON frameworks, including Json.NET, support it.IsoDateTimeConverterFrom Json.NET 4.5 and onwards dates are written using the ISO 8601
format by default, and using this converter is unnecessary.IsoDateTimeConverter serializes a DateTime to an ISO 8601http://en.wikipedia.org/wiki/ISO_8601_blank formatted
string: "2009-02-15T00:00:00Z"The IsoDateTimeConverter class has a property, DateTimeFormat, to
further customize the formatted string.T:Newtonsoft.Json.DateFormatHandlingT:Newtonsoft.Json.DateTimeZoneHandlingT:Newtonsoft.Json.Converters.JavaScriptDateTimeConverterT:Newtonsoft.Json.Converters.IsoDateTimeConverter
================================================
FILE: Doc/Introduction.aml
================================================
Json.NET is a popular high-performance JSON framework for .NETBenefits and FeaturesFlexible JSON serializer for converting between .NET objects and JSONLINQ to JSON for manually reading and writing JSON High performance: faster than .NET's built-in JSON serializersWrite indented, easy-to-read JSONConvert JSON to and from XMLSupports .NET Standard 2.0https://github.com/dotnet/standard/blob/master/docs/versions.md_blank,
.NET 2, .NET 3.5, .NET 4, .NET 4.5, Silverlight, Windows Phone and Windows 8 StoreThe JSON serializer in Json.NET is a good choice when the JSON you are reading or writing maps closely to a .NET class.LINQ to JSON is good for situations where you are only interested in
getting values from JSON, you don't have a class to serialize or deserialize to,
or the JSON is radically different from your class and you need to manually read
and write from your objects.Getting StartedHistoryJson.NET grew out of projects I was working on in late 2005 involving JavaScript,
AJAX, and .NET. At the time there were no libraries for working with JavaScript in
.NET, so I made my own.Starting out as a couple of static methods for escaping JavaScript strings, Json.NET
evolved as features were added. To add support for reading JSON a major refactor
was required, and Json.NET was split into the three major classes it still uses
today: JsonReader, JsonWriter and JsonSerializer.Json.NET was first released in June 2006. Since then Json.NET has been downloaded
hundreds of thousands of times by developers from around the world. It is used in many major open
source projects, including: Monohttp://www.mono-project.com/_blank,
an open source implementation
of the .NET framework; RavenDBhttp://ravendb.net/_blank,
a JSON based document database; ASP.NET SignalRhttp://signalr.net/_blank,
an async library for building real-time, multi-user interactive web applications; and ASP.NET Corehttp://www.asp.net_blank,
Microsoft's web app and service framework.
================================================
FILE: Doc/JsonNetVsDotNetSerializers.aml
================================================
Json.NET offers many features not found in the JavaScriptSerializer and DataContractSerializer that come with .NET.Feature Comparison
Json.NETDataContractJsonSerializerJavaScriptSerializerSupports JSONSupports BSONSupports JSONPathSupports .NET 2.0Supports .NET 3.5Supports .NET 4.0Supports .NET 4.5Supports SilverlightSupports Windows PhoneSupports Windows StoreSupports XamarinOpen SourceMIT LicenseLINQ to JSONThread SafeXPath-like JSON query syntaxIndented JSON supportEfficient dictionary serializationhttp://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net_blankNonsensical dictionary serializationhttp://stackoverflow.com/questions/4559991/any-way-to-make-datacontractjsonserializer-serialize-dictionaries-properly_blankDeserializes IList, IEnumerable, ICollection, IDictionary propertiesSerializes circular referencesSupports serializing objects by referenceDeserializes polymorphic properties and collectionsSerializes and deserializes multidimensional arraysSupports including type names with JSONGlobally customize serialization processSupports excluding null values when serializingSupports SerializationBinderConditional property serializationIncludes line number information in errorsConverts XML to JSON and JSON to XMLJSON Schema validationJSON Schema generation from .NET typesCamel case JSON property namesNon-default constructors supportSerialization error handlingSupports populating an existing objectEfficiently serializes byte arrays as base64 textHandles NaN, Infinity, -Infinity and undefinedHandles JavaScript constructorsSerializes .NET 4.0 dynamic objectsSerializes ISerializable objectsSupports serializing enums to their text nameJSON recursion limit supportAttribute property name customizationAttribute property order customizationAttribute property required customizationSupports ISO8601 datesSupports JavaScript constructor datesSupports Microsoft AJAX datesUnquoted property names supportRaw JSON supportSupports reading and writing commentsSerializes anonymous typesDeserializes anonymous typesOpt-in mode serializationOpt-out mode serializationField (Serializable) mode serializationEfficiently stream reading and writing JSONSingle or double quote JSON contentSupports overriding a type's serializationSupports OnDeserialized, OnSerializing, OnSerialized and OnDeserializing attributesSupports serializing private propertiesDataMember attribute supportMetdataType attribute supportDefaultValue attribute supportSerializes DataSets and DataTablesSerializes Entity FrameworkSerializes nHibernateCase-insensitive property deserializationDiagnostic tracingSerializes read-only and immutable collectionsSupports serialization extension dataSerializes F# discriminated unionsSerializes F# collectionsSupports merging JSON
BenchmarksJson.NET Performance
================================================
FILE: Doc/JsonSchema.aml
================================================
Json.NET supports the JSON Schema standard via the T:Newtonsoft.Json.Schema.JsonSchema
and T:Newtonsoft.Json.JsonValidatingReader classes. It sits under
the N:Newtonsoft.Json.Schema namespace.JSON Schema is used to validate the structure and
data types of a piece of JSON, similar to XML Schema for XML. You can read more about JSON Schema at
json-schema.orghttp://json-schema.org/_blankObsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Validating with JSON SchemaThe simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then
use the M:Newtonsoft.Json.Schema.Extensions.IsValid(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema)
method with the JSON Schema.To get validation error messages, use the
M:Newtonsoft.Json.Schema.Extensions.IsValid(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema,System.Collections.Generic.IList{System.String}@)
or
M:Newtonsoft.Json.Schema.Extensions.Validate(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema,Newtonsoft.Json.Schema.ValidationEventHandler)
overloads.Internally IsValid uses T:Newtonsoft.Json.JsonValidatingReader
to perform the JSON Schema validation. To skip the overhead of loading JSON into a JObject/JArray, validating
the JSON, and then deserializing the JSON into a class, JsonValidatingReader can be used with JsonSerializer to validate JSON while the object is being deserialized.Creating JSON SchemasThe simplest way to get a T:Newtonsoft.Json.Schema.JsonSchema object is to load it from a string or a file.It is also possible to create JsonSchema objects in code.T:Newtonsoft.Json.Schema.JsonSchemaT:Newtonsoft.Json.JsonValidatingReader
================================================
FILE: Doc/LINQtoJSON.aml
================================================
LINQ to JSON is an API for working with JSON objects.
It has been designed with LINQ in mind to enable quick querying
and creation of JSON objects. LINQ to JSON sits under the
N:Newtonsoft.Json.Linq
namespace.TopicsSelect a topic below for more information:T:Newtonsoft.Json.Linq.JObjectT:Newtonsoft.Json.Linq.JArrayT:Newtonsoft.Json.Linq.JValue
================================================
FILE: Doc/ParsingLINQtoJSON.aml
================================================
LINQ to JSON has methods available for parsing JSON from a string or loading JSON directly from a file.Parsing JSON textJSON values can be read from a string using
M:Newtonsoft.Json.Linq.JToken.Parse(System.String).Loading JSON from a fileJSON can also be loaded directly from a file using M:Newtonsoft.Json.Linq.JToken.ReadFrom(Newtonsoft.Json.JsonReader).M:Newtonsoft.Json.Linq.JToken.Parse(System.String)M:Newtonsoft.Json.Linq.JToken.ReadFrom(Newtonsoft.Json.JsonReader)
================================================
FILE: Doc/Performance.aml
================================================
Out of the box Json.NET is faster than DataContractJsonSerializer and JavaScriptSerializer.
Here are some tips to make it go even faster.Reuse Contract ResolverThe T:Newtonsoft.Json.Serialization.IContractResolver resolves .NET types to contracts that are used during serialization inside JsonSerializer.
Creating a contract involves inspecting a type with slow reflection, so contracts are typically
cached by implementations of IContractResolver like T:Newtonsoft.Json.Serialization.DefaultContractResolver.To avoid the overhead of recreating contracts every time you use JsonSerializer you should create the contract resolver once and reuse it.
Note that if you are not using a contract resolver then a shared internal instance is automatically used when serializing and deserializing.
Optimize Memory UsageTo keep an application consistently fast, it is important to minimize the
amount of time the .NET framework spends performing garbage collectionhttp://msdn.microsoft.com/en-us/library/ms973837.aspx_blank.
Allocating too many objects or allocating very large objects can slow down or even
halt an application while garbage collection is in progress.
To minimize memory usage and the number of objects allocated, Json.NET supports
serializing and deserializing directly to a stream. Reading or writing JSON a piece at a time, instead of having
the entire JSON string loaded into memory, is especially important when working with JSON
documents greater than 85kb in size to avoid the JSON string ending up in the large object heaphttp://msdn.microsoft.com/en-us/magazine/cc534993.aspx_blank.JsonConvertersPassing a T:Newtonsoft.Json.JsonConverter to SerializeObject or DeserializeObject provides a simple way to completely
change how an object is serialized. There is, however, a small amount of overhead; the CanConvert method is called for every
value to check whether serialization should be handled by that JsonConverter.There are a couple of ways to continue to use JsonConverters without any overhead. The simplest way
is to specify the JsonConverter using the T:Newtonsoft.Json.JsonConverterAttribute. This attribute tells the serializer
to always use that converter when serializing and deserializing the type, without the check.If the class you want to convert isn't your own and you're unable to use an attribute, a JsonConverter can still be used by
creating your own T:Newtonsoft.Json.Serialization.IContractResolver.The IContractResolver in the example above will set all DateTimes to use the JavaScriptDateConverter.Manually SerializeThe absolute fastest way to read and write JSON is to use JsonTextReader/JsonTextWriter directly to manually serialize types.
Using a reader or writer directly skips any of the overhead from a serializer, such as reflection.
If performance is important and you don't mind writing more code to get it, then this is your best choice. You can read more about using JsonReader/JsonWriter here:
BenchmarksJson.NET PerformanceT:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.JsonConverterT:Newtonsoft.Json.JsonConverterAttributeT:Newtonsoft.Json.JsonTextWriterT:Newtonsoft.Json.JsonTextReader
================================================
FILE: Doc/PreserveObjectReferences.aml
================================================
By default Json.NET will serialize all objects it encounters by value.
If a list contains two Person references and both references point to the
same object, then the JsonSerializer will write out all the names and values
for each reference.In most cases this is the desired result, but in certain scenarios
writing the second item in the list as a reference to the first is a better
solution. If the above JSON was deserialized now, then the returned list would
contain two completely separate Person objects with the same values. Writing
references by value will also cause problems on objects where a circular
reference occurs.PreserveReferencesHandlingSetting T:Newtonsoft.Json.PreserveReferencesHandling will track object references
when serializing and deserializing JSON.The first Person in the list is serialized with the addition of an
object ID. The second Person in JSON is now only a reference to the first.With PreserveReferencesHandling on, now only one Person object is created
on deserialization and the list contains two references to it, mirroring
what we started with.
Metadata properties like $id must be located at the beginning of a JSON object to be successfully detected during deserialization. If you can't control
the order of properties in your JSON object then T:Newtonsoft.Json.MetadataPropertyHandling can be used to remove this restriction.
References cannot be preserved when a value is set via a non-default constructor.
With a non-default constructor, child values must be created before the parent value so they can be passed into
the constructor, making tracking reference impossible.
T:System.Runtime.Serialization.ISerializable types are an example
of a class whose values are populated with a non-default constructor and won't work with PreserveReferencesHandling.IsReferenceThe PreserveReferencesHandling setting on the JsonSerializer will
change how all objects are serialized and deserialized. For fine grain
control over which objects and members should be serialized as a
reference there is the IsReference property on the JsonObjectAttribute,
JsonArrayAttribute and JsonPropertyAttribute.Setting IsReference on JsonObjectAttribute or JsonArrayAttribute to
true will mean the JsonSerializer will always serialize the type the
attribute is against as a reference. Setting IsReference on the
JsonPropertyAttribute to true will serialize only that property as a
reference.IReferenceResolverTo customize how references are generated and resolved the
T:Newtonsoft.Json.Serialization.IReferenceResolver
interface is available to inherit from and use with
the JsonSerializer.T:Newtonsoft.Json.PreserveReferencesHandling
================================================
FILE: Doc/QueryingLINQtoJSON.aml
================================================
LINQ to JSON provides a number of methods for getting data from its objects. The index methods on JObject/JArray let you quickly get data by its property name
on an object or index in a collection, while M:Newtonsoft.Json.Linq.JToken.Children lets you get ranges
of data as IEnumerable<JToken> to then query using LINQ.Getting values by Property Name or Collection IndexThe simplest way to get a value from LINQ to JSON is to use the
P:Newtonsoft.Json.Linq.JToken.Item(System.Object) index on
JObject/JArray and then cast the returned T:Newtonsoft.Json.Linq.JValue to the type you want.
Querying with LINQJObject/JArray can also be queried using LINQ. M:Newtonsoft.Json.Linq.JToken.Children
returns the children values of a JObject/JArray
as an IEnumerable<JToken> that can then be queried with the standard Where/OrderBy/Select LINQ operators.M:Newtonsoft.Json.Linq.JToken.Children returns all the children of a token. If it is a
JObject it will return a collection of properties to work with, and if
it is a JArray you will get a collection of the array's values.LINQ to JSON can also be used to manually convert JSON to a .NET object.Manually serializing and deserializing between .NET objects is useful when you are
working with JSON that doesn't closely match your .NET objects.P:Newtonsoft.Json.Linq.JToken.Item(System.Object)M:Newtonsoft.Json.Linq.JToken.Children
================================================
FILE: Doc/ReadingWritingJSON.aml
================================================
To manually read and write JSON, Json.NET provides the
T:Newtonsoft.Json.JsonReader
and
T:Newtonsoft.Json.JsonWriter classes.JsonTextReader and JsonTextWriterJsonReader and JsonWriter are low-level classes and are primarily for internal use by Json.NET.
To quickly work with JSON, either the serializer - - or using is recommended.
T:Newtonsoft.Json.JsonTextReader
and T:Newtonsoft.Json.JsonTextWriter
are used to read and write JSON text.
The JsonTextWriter has a number of settings on it to control how JSON is formatted
when it is written. These options include formatting, indentation character, indent
count, and quote character.JsonTextReader has settings on it for reading different date formats, time zones, and
the cultures when reading text values.JTokenReader and JTokenWriterT:Newtonsoft.Json.Linq.JTokenReader
and T:Newtonsoft.Json.Linq.JTokenWriter
read and write LINQ to JSON objects. They are located in the
N:Newtonsoft.Json.Linq
namespace. These objects allow you to use LINQ to JSON objects with objects that
read and write JSON, such as the JsonSerializer. For example you can deserialize
from a LINQ to JSON object into a regular .NET object and vice versa.T:Newtonsoft.Json.JsonReaderT:Newtonsoft.Json.JsonWriterT:Newtonsoft.Json.Linq.JTokenReaderT:Newtonsoft.Json.Linq.JTokenWriterT:Newtonsoft.Json.Bson.BsonReaderT:Newtonsoft.Json.Bson.BsonWriter
================================================
FILE: Doc/ReducingSerializedJSONSize.aml
================================================
One of the common problems encountered when serializing .NET objects to
JSON is that the JSON ends up containing a lot of unwanted properties and values.
This can be especially significant when returning JSON to the client. More JSON
means more bandwidth and a slower website.To solve the issue of unwanted JSON, Json.NET has a range of built-in
options to fine-tune what gets written from a serialized object.JsonIgnoreAttribute and DataMemberAttributeBy default Json.NET will include all of a class's public properties and fields
in the JSON it creates. Adding the
T:Newtonsoft.Json.JsonIgnoreAttribute
to a property tells the serializer to always skip writing it to the JSON result.If a class has many properties and you only want to serialize a small subset
of them, then adding JsonIgnore to all the others will be tedious and error prone.
The way to tackle this scenario is to add the
T:System.Runtime.Serialization.DataContractAttribute
to the class and
T:System.Runtime.Serialization.DataMemberAttribute
to the properties to serialize. This is opt-in
serialization - only the properties you mark up will be serialized, unlike
opt-out serialization using JsonIgnoreAttribute.FormattingJSON written by the serializer with an option of
T:Newtonsoft.Json.Formatting
set to Indented produces
nicely formatted, easy-to-read JSON that is great for readability when you are
developing. Formatting.None on the other hand keeps the JSON result small, skipping
all unnecessary spaces and line breaks to produce the most compact and efficient
JSON possible.NullValueHandlingT:Newtonsoft.Json.NullValueHandling
is an option on the JsonSerializer and controls how the
serializer handles properties with a null value. By setting a value of
NullValueHandling.Ignore the JsonSerializer skips writing any properties that have
a value of null.NullValueHandling can also be customized on individual properties
using the
T:Newtonsoft.Json.JsonPropertyAttribute.
The JsonPropertyAttribute value of
NullValueHandling will override the setting on the JsonSerializer for that
property.DefaultValueHandlingT:Newtonsoft.Json.DefaultValueHandling
is an option on the JsonSerializer and controls how the serializer handles
properties with a default value. Setting a value of DefaultValueHandling.Ignore
will make the JsonSerializer skip writing any properties that have a default
value to the JSON result. For object references this will be null. For value
types like int and DateTime the serializer will skip the default uninitialized
value for that value type.Json.NET also allows you to customize what the default value of an individual
property is using the
T:System.ComponentModel.DefaultValueAttribute.
For example, if a string property called
Department always returns an empty string in its default state and you don't want
that empty string in your JSON, then placing the DefaultValueAttribute on Department
with that value will mean Department is no longer written to JSON unless it has a
value.DefaultValueHandling can also be customized on individual properties using
the T:Newtonsoft.Json.JsonPropertyAttribute.
The JsonPropertyAttribute value of DefaultValueHandling
will override the setting on the JsonSerializer for that property.IContractResolverFor more flexibility, the
T:Newtonsoft.Json.Serialization.IContractResolver
provides an interface to customize
almost every aspect of how a .NET object gets serialized to JSON, including changing
serialization behavior at runtime.T:Newtonsoft.Json.FormattingT:Newtonsoft.Json.JsonIgnoreAttributeT:Newtonsoft.Json.DefaultValueHandlingT:Newtonsoft.Json.NullValueHandling
================================================
FILE: Doc/Samples/Bson/DeserializeFromBson.aml
================================================
This sample deserializes BSON to an object.Sample
================================================
FILE: Doc/Samples/Bson/DeserializeFromBsonCollection.aml
================================================
This sample sets P:Newtonsoft.Json.Bson.BsonReader.ReadRootValueAsArray
to true so the root BSON value is correctly read
as an array instead of an object and deserializes BSON to a collection.Sample
================================================
FILE: Doc/Samples/Bson/SerializeToBson.aml
================================================
This sample serializes an object to BSON.Sample
================================================
FILE: Doc/Samples/Json/CustomJsonReader.aml
================================================
This sample creates a custom T:Newtonsoft.Json.JsonReader.Sample
================================================
FILE: Doc/Samples/Json/CustomJsonWriter.aml
================================================
This sample creates a custom T:Newtonsoft.Json.JsonWriter.Sample
================================================
FILE: Doc/Samples/Json/ReadJsonWithJsonTextReader.aml
================================================
This sample reads JSON using the T:Newtonsoft.Json.JsonTextReader.Sample
================================================
FILE: Doc/Samples/Json/ReadMultipleContentWithJsonReader.aml
================================================
This sample sets P:Newtonsoft.Json.JsonReader.SupportMultipleContent
to true so that multiple JSON fragments can be read from a T:System.IO.Stream or
T:System.IO.TextReader.Sample
================================================
FILE: Doc/Samples/Json/WriteJsonWithJsonTextWriter.aml
================================================
This sample writes JSON using the T:Newtonsoft.Json.JsonTextWriter.Sample
================================================
FILE: Doc/Samples/JsonPath/ErrorWhenNoMatchQuery.aml
================================================
This sample loads JSON and then queries values from it using Overload:Newtonsoft.Json.Linq.JToken.SelectToken. An error is thrown when part of the JSON path is not found.Sample
================================================
FILE: Doc/Samples/JsonPath/QueryJsonSelectToken.aml
================================================
This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String).Sample
================================================
FILE: Doc/Samples/JsonPath/QueryJsonSelectTokenEscaped.aml
================================================
This sample loads JSON with properties that need to be escaped when queried with M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String).Sample
================================================
FILE: Doc/Samples/JsonPath/QueryJsonSelectTokenJsonPath.aml
================================================
This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String) with a JSONPathhttp://stackoverflow.com/tags/jsonpath_blank query.Sample
================================================
FILE: Doc/Samples/JsonPath/QueryJsonSelectTokenWithLinq.aml
================================================
This sample loads JSON and then queries values from it using a combination of M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String)
and LINQ operators.Sample
================================================
FILE: Doc/Samples/JsonPath/RegexQuery.aml
================================================
This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String) with a regex JSON Path.Sample
================================================
FILE: Doc/Samples/JsonPath/StrictEqualsQuery.aml
================================================
This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String) with a strict equals JSON Path.Sample
================================================
FILE: Doc/Samples/Linq/Clone.aml
================================================
This sample recursively clones a T:Newtonsoft.Json.Linq.JToken
and all its children using M:Newtonsoft.Json.Linq.JToken.DeepClone.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonAnonymousObject.aml
================================================
This sample creates a T:Newtonsoft.Json.Linq.JObject
from an anonymous type.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonCollectionInitializer.aml
================================================
This sample creates T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray instances using
the C# collection initializer syntax.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonDeclaratively.aml
================================================
This sample creates T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray instances declaratively
using LINQ.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonDynamic.aml
================================================
This sample creates T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray instances using
the C# dynamic functionality.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonJTokenWriter.aml
================================================
This sample creates T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray instances using
a T:Newtonsoft.Json.Linq.JTokenWriter.Sample
================================================
FILE: Doc/Samples/Linq/CreateJsonManually.aml
================================================
This sample creates T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray instances one at a time
programatically.Sample
================================================
FILE: Doc/Samples/Linq/CreateReader.aml
================================================
This sample creates a T:Newtonsoft.Json.Linq.JTokenReader
from a T:Newtonsoft.Json.Linq.JToken.Sample
================================================
FILE: Doc/Samples/Linq/CreateWriter.aml
================================================
This sample creates a T:Newtonsoft.Json.Linq.JTokenWriter
from a T:Newtonsoft.Json.Linq.JToken.Sample
================================================
FILE: Doc/Samples/Linq/DeepEquals.aml
================================================
This sample compares T:Newtonsoft.Json.Linq.JToken
instances using M:Newtonsoft.Json.Linq.JToken.DeepEquals(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Linq.JToken),
comparing the token and all child tokens.Sample
================================================
FILE: Doc/Samples/Linq/DeserializeWithLinq.aml
================================================
This sample uses LINQ to JSON to manually convert JSON to a .NET type.Sample
================================================
FILE: Doc/Samples/Linq/FromObject.aml
================================================
This sample converts .NET values to LINQ to JSON using
M:Newtonsoft.Json.Linq.JToken.FromObject(System.Object).Sample
================================================
FILE: Doc/Samples/Linq/JObjectProperties.aml
================================================
This sample gets an object's T:Newtonsoft.Json.Linq.JProperty
collection using M:Newtonsoft.Json.Linq.JObject.Properties.Sample
================================================
FILE: Doc/Samples/Linq/JTokenAnnotation.aml
================================================
This sample uses annotations with LINQ to JSON objects.Sample
================================================
FILE: Doc/Samples/Linq/JValueCast.aml
================================================
This sample casts T:Newtonsoft.Json.Linq.JValue
instances to .NET values.Sample
================================================
FILE: Doc/Samples/Linq/JValueValue.aml
================================================
This sample gets T:Newtonsoft.Json.Linq.JValue
internal values using P:Newtonsoft.Json.Linq.JValue.Value.Sample
================================================
FILE: Doc/Samples/Linq/MergeJson.aml
================================================
This sample merges LINQ to JSON objects.Sample
================================================
FILE: Doc/Samples/Linq/ModifyJson.aml
================================================
This sample loads JSON, modifies T:Newtonsoft.Json.Linq.JObject
and T:Newtonsoft.Json.Linq.JArray
instances and then writes the JSON back out again.Sample
================================================
FILE: Doc/Samples/Linq/ParseJsonAny.aml
================================================
This sample parses JSON using
M:Newtonsoft.Json.Linq.JToken.Parse(System.String).Sample
================================================
FILE: Doc/Samples/Linq/ParseJsonArray.aml
================================================
This sample parses a JSON array using
M:Newtonsoft.Json.Linq.JArray.Parse(System.String).Sample
================================================
FILE: Doc/Samples/Linq/ParseJsonObject.aml
================================================
This sample parses a JSON object using
M:Newtonsoft.Json.Linq.JObject.Parse(System.String).Sample
================================================
FILE: Doc/Samples/Linq/QueryJson.aml
================================================
This sample loads JSON and then queries values from it using
P:Newtonsoft.Json.Linq.JToken.Item(System.Object)
indexer and then casts the returned tokens to .NET values.Sample
================================================
FILE: Doc/Samples/Linq/QueryJsonDynamic.aml
================================================
This sample loads JSON and then queries values from it using
C# dynamic functionality.Sample
================================================
FILE: Doc/Samples/Linq/QueryJsonLinq.aml
================================================
This sample loads JSON and then queries values from it using LINQ operators.Sample
================================================
FILE: Doc/Samples/Linq/ReadJTokenFromBson.aml
================================================
This sample reads a T:Newtonsoft.Json.Linq.JObject
from BSON using T:Newtonsoft.Json.Bson.BsonReader.Sample
================================================
FILE: Doc/Samples/Linq/ReadJson.aml
================================================
This sample reads JSON from a file into a T:Newtonsoft.Json.Linq.JObject.Sample
================================================
FILE: Doc/Samples/Linq/SerializeWithLinq.aml
================================================
This sample uses LINQ to JSON to manually convert a .NET type to JSON.Sample
================================================
FILE: Doc/Samples/Linq/ToObjectComplex.aml
================================================
This sample converts LINQ to JSON objects to .NET types using
M:Newtonsoft.Json.Linq.JToken.ToObject``1.Sample
================================================
FILE: Doc/Samples/Linq/ToObjectGeneric.aml
================================================
This sample converts LINQ to JSON objects to .NET types using
M:Newtonsoft.Json.Linq.JToken.ToObject``1.Sample
================================================
FILE: Doc/Samples/Linq/ToObjectType.aml
================================================
This sample converts LINQ to JSON objects to .NET types using
M:Newtonsoft.Json.Linq.JToken.ToObject(System.Type).Sample
================================================
FILE: Doc/Samples/Linq/ToString.aml
================================================
This sample converts LINQ to JSON objects to JSON.Sample
================================================
FILE: Doc/Samples/Linq/ToStringJsonConverter.aml
================================================
This sample uses a T:Newtonsoft.Json.JsonConverter
to customize converting LINQ to JSON objects to JSON.Sample
================================================
FILE: Doc/Samples/Linq/WriteJTokenToBson.aml
================================================
This sample writes a T:Newtonsoft.Json.Linq.JObject
to BSON using T:Newtonsoft.Json.Bson.BsonWriter.Sample
================================================
FILE: Doc/Samples/Linq/WriteToJsonFile.aml
================================================
This sample writes LINQ to JSON objects to a file.Sample
================================================
FILE: Doc/Samples/Samples.aml
================================================
Over 100 code samples covering Json.NET's most commonly used functionality.SamplesSerializing JSON - Serializing and deserializing JSON, serializer settings and serialization attributesLINQ to JSON - Parsing, querying, modifying and writing JSONJSON Schema - Loading schemas and validating JSON. Note that JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.Converting XML - Converting JSON to XML and XML to JSONBSON - Serializing and deserializing BSONReading and Writing JSON - Reading JSON with JsonTextReader, writing JSON with JsonTextWriter
================================================
FILE: Doc/Samples/Schema/CreateJsonSchemaManually.aml
================================================
This sample creates a new T:Newtonsoft.Json.Schema.JsonSchema
instance manually in code.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/JTokenIsValid.aml
================================================
This sample validates a T:Newtonsoft.Json.Linq.JObject
using the M:Newtonsoft.Json.Schema.Extensions.IsValid(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema)
extension method.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/JTokenIsValidWithMessages.aml
================================================
This sample validates a T:Newtonsoft.Json.Linq.JObject
using the M:Newtonsoft.Json.Schema.Extensions.IsValid(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema)
extension method and returns error messages.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/JTokenValidateWithEvent.aml
================================================
This sample validates a T:Newtonsoft.Json.Linq.JObject
using the M:Newtonsoft.Json.Schema.Extensions.IsValid(Newtonsoft.Json.Linq.JToken,Newtonsoft.Json.Schema.JsonSchema)
extension method and raises an event for each validation error.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/JsonSchemaParse.aml
================================================
This sample parses a T:Newtonsoft.Json.Schema.JsonSchema
from JSONObsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/JsonValidatingReaderAndSerializer.aml
================================================
This sample validates JSON while deserializing an object using
T:Newtonsoft.Json.JsonValidatingReader.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/LoadJsonSchemaFromFile.aml
================================================
This sample loads a T:Newtonsoft.Json.Schema.JsonSchema
from a file.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/RefJsonSchemaResolver.aml
================================================
This sample uses a T:Newtonsoft.Json.Schema.JsonSchemaResolver
to resolve schema references from different JSON documents.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Schema/SaveJsonSchemaToFile.aml
================================================
This sample saves a T:Newtonsoft.Json.Schema.JsonSchema
to a file.Obsolete. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemahttps://www.newtonsoft.com/jsonschema_blank
for more details.
Sample
================================================
FILE: Doc/Samples/Serializer/CustomContractResolver.aml
================================================
This sample creates a custom T:Newtonsoft.Json.Serialization.IContractResolver
that only serializes a type's properties that begin with a specified character.Sample
================================================
FILE: Doc/Samples/Serializer/CustomJsonConverter.aml
================================================
This sample creates a custom T:Newtonsoft.Json.JsonConverter
that overrides serialization to add a keys property.Sample
================================================
FILE: Doc/Samples/Serializer/CustomJsonConverterGeneric.aml
================================================
This sample creates a custom converter from JsonConverter<T>
that overrides serialization for the Version class with a custom display string.Sample
================================================
FILE: Doc/Samples/Serializer/CustomTraceWriter.aml
================================================
This sample creates a custom T:Newtonsoft.Json.Serialization.ITraceWriter
that writes to
NLoghttp://nlog-project.org/_blank.Sample
================================================
FILE: Doc/Samples/Serializer/DataContractAndDataMember.aml
================================================
This sample shows how .NET Framework attributes such as
T:System.Runtime.Serialization.DataContractAttribute,
T:System.Runtime.Serialization.DataMemberAttribute and
T:System.NonSerializedAttribute
can be used with Json.NET instead of Json.NET's own attributes.Sample
================================================
FILE: Doc/Samples/Serializer/DefaultSettings.aml
================================================
This sample serializes and deserializes JSON using P:Newtonsoft.Json.JsonConvert.DefaultSettings.Sample
================================================
FILE: Doc/Samples/Serializer/DefaultValueAttributeIgnore.aml
================================================
This sample uses the T:System.ComponentModel.DefaultValueAttribute
to override the default value for a property and exclude it from serialization using
T:Newtonsoft.Json.DefaultValueHandling.Sample
================================================
FILE: Doc/Samples/Serializer/DefaultValueHandlingIgnore.aml
================================================
This sample uses the T:Newtonsoft.Json.DefaultValueHandling setting to
not serialize properties with a default value.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeAnonymousType.aml
================================================
This sample deserializes JSON into an anonymous type.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeCollection.aml
================================================
This sample deserializes JSON into a collection.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeConstructorHandling.aml
================================================
This sample uses the T:Newtonsoft.Json.ConstructorHandling setting to
successfully deserialize the class using its non-public constructor.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeCustomCreationConverter.aml
================================================
This sample creates a class that inherits from T:Newtonsoft.Json.Converters.CustomCreationConverter`1
that instantiates Employee instances for the Person type.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeDataSet.aml
================================================
This sample deserializes JSON to a T:System.Data.DataSet.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeDateFormatString.aml
================================================
This sample uses the DateFormatString
setting to control how T:System.DateTime and T:System.DateTimeOffset are deserialized.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeDictionary.aml
================================================
This sample deserializes JSON into a dictionary.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeExtensionData.aml
================================================
This sample deserializes JSON to an object with extension data.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeImmutableCollections.aml
================================================
This sample deserializes JSON into an immutable collection.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeMetadataPropertyHandling.aml
================================================
This sample deserializes JSON with T:Newtonsoft.Json.MetadataPropertyHandling
set to ReadAhead so that metadata properties do not need to be at the start of an object.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeMissingMemberHandling.aml
================================================
This sample attempts to deserialize JSON with T:Newtonsoft.Json.MissingMemberHandling
set to error and a JSON property that doesn't match to a member, causing an exception.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeObject.aml
================================================
This sample deserializes JSON to an object.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeObjectCreationHandling.aml
================================================
This sample deserializes JSON with T:Newtonsoft.Json.ObjectCreationHandling
set to Replace so that collection values aren't duplicated.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeWithDependencyInjection.aml
================================================
This sample deserializes JSON using dependency injection.Sample
================================================
FILE: Doc/Samples/Serializer/DeserializeWithJsonSerializerFromFile.aml
================================================
This sample deserializes JSON retrieved from a file.Sample
================================================
FILE: Doc/Samples/Serializer/ErrorHandlingAttribute.aml
================================================
This sample uses T:Newtonsoft.Json.Serialization.OnErrorAttribute to ignore the exception thrown setting the Roles property.Sample
================================================
FILE: Doc/Samples/Serializer/ErrorHandlingEvent.aml
================================================
This sample uses the P:Newtonsoft.Json.JsonSerializerSettings.Error event
to ignore the exceptions thrown from the invalid date strings.Sample
================================================
FILE: Doc/Samples/Serializer/JsonConstructorAttribute.aml
================================================
This sample uses the
T:Newtonsoft.Json.JsonConstructorAttribute
to specify that a constructor should be used to create a class during deserialization.Sample
================================================
FILE: Doc/Samples/Serializer/JsonConverterAttributeClass.aml
================================================
This sample uses the
T:Newtonsoft.Json.JsonConverterAttribute
to specify that a T:Newtonsoft.Json.JsonConverter
should be used when serializing and deserializing a class.Sample
================================================
FILE: Doc/Samples/Serializer/JsonConverterAttributeProperty.aml
================================================
This sample uses the
T:Newtonsoft.Json.JsonConverterAttribute
to specify that a T:Newtonsoft.Json.JsonConverter
should be used when serializing and deserializing a property.Sample
================================================
FILE: Doc/Samples/Serializer/JsonObjectAttributeOptIn.aml
================================================
This sample uses
T:Newtonsoft.Json.JsonObjectAttribute
and T:Newtonsoft.Json.MemberSerialization to specify that
only properties that have been explicitly specified with T:Newtonsoft.Json.JsonPropertyAttribute
should be serialized.Sample
================================================
FILE: Doc/Samples/Serializer/JsonObjectAttributeOverrideIEnumerable.aml
================================================
This sample uses T:Newtonsoft.Json.JsonObjectAttribute
to serialize a class that implements T:System.Collections.Generic.IEnumerable`1 as
a JSON object instead of a JSON array.Sample
================================================
FILE: Doc/Samples/Serializer/JsonPropertyItemLevelSetting.aml
================================================
This sample uses T:Newtonsoft.Json.JsonPropertyAttribute
to change how the property value's items are serialized,
e.g. setting ItemIsReference to true on a property with a collection will serialize all the collection's items
with reference tracking enabled.Sample
================================================
FILE: Doc/Samples/Serializer/JsonPropertyName.aml
================================================
This sample uses T:Newtonsoft.Json.JsonPropertyAttribute
to change the names of properties when they are serialized to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/JsonPropertyOrder.aml
================================================
This sample uses T:Newtonsoft.Json.JsonPropertyAttribute
to order of properties when they are serialized to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/JsonPropertyPropertyLevelSetting.aml
================================================
This sample uses T:Newtonsoft.Json.JsonPropertyAttribute
to change how the property value is serialized.Sample
================================================
FILE: Doc/Samples/Serializer/JsonPropertyRequired.aml
================================================
This sample uses T:Newtonsoft.Json.JsonPropertyAttribute
to set T:Newtonsoft.Json.Required which is used during deserialization
to validate the presence of required JSON properties.Sample
================================================
FILE: Doc/Samples/Serializer/MaxDepth.aml
================================================
This sample uses the P:Newtonsoft.Json.JsonSerializerSettings.MaxDepth setting to constrain JSON
to a maximum depth when deserializing.Sample
================================================
FILE: Doc/Samples/Serializer/NamingStrategyAttributes.aml
================================================
This sample uses T:Newtonsoft.Json.Serialization.NamingStrategy
types specified on attributes to control serialized property names.Sample
================================================
FILE: Doc/Samples/Serializer/NamingStrategyCamelCase.aml
================================================
This sample uses a T:Newtonsoft.Json.Serialization.CamelCaseNamingStrategy
specified using a contract resolver to camel case serialized property names.Sample
================================================
FILE: Doc/Samples/Serializer/NamingStrategySkipDictionaryKeys.aml
================================================
This sample configures a T:Newtonsoft.Json.Serialization.CamelCaseNamingStrategy
to not camel case dictionary keys.Sample
================================================
FILE: Doc/Samples/Serializer/NamingStrategySkipSpecifiedNames.aml
================================================
This sample configures a T:Newtonsoft.Json.Serialization.CamelCaseNamingStrategy
to not camel case properties that already have a name specified with an attribute.Sample
================================================
FILE: Doc/Samples/Serializer/NamingStrategySnakeCase.aml
================================================
This sample uses a T:Newtonsoft.Json.Serialization.SnakeCaseNamingStrategy
specified using a contract resolver to snake case serialized property names.Sample
================================================
FILE: Doc/Samples/Serializer/NullValueHandlingIgnore.aml
================================================
This sample serializes an object to JSON with T:Newtonsoft.Json.NullValueHandling
set to Ignore so that properties with a default value of null aren't included in the JSON result.Sample
================================================
FILE: Doc/Samples/Serializer/PopulateObject.aml
================================================
This sample populates an existing object instance with values from JSON.Sample
================================================
FILE: Doc/Samples/Serializer/PreserveReferencesHandlingObject.aml
================================================
This sample shows how the T:Newtonsoft.Json.PreserveReferencesHandling
setting can be used to serialize values by reference instead of by value.Sample
================================================
FILE: Doc/Samples/Serializer/PropertyJsonIgnore.aml
================================================
This sample uses the T:Newtonsoft.Json.JsonIgnoreAttribute
to exclude a property from serialization.Sample
================================================
FILE: Doc/Samples/Serializer/ReferenceLoopHandlingIgnore.aml
================================================
This sample sets T:Newtonsoft.Json.ReferenceLoopHandling
to Ignore so that looping values are excluded from serialization instead of throwing an exception.Sample
================================================
FILE: Doc/Samples/Serializer/SerializationCallbackAttributes.aml
================================================
This sample uses serialization callback attributes
(T:System.Runtime.Serialization.OnSerializingAttribute,
T:System.Runtime.Serialization.OnSerializedAttribute,
T:System.Runtime.Serialization.OnDeserializingAttribute,
T:System.Runtime.Serialization.OnDeserializedAttribute)
to manipulate an object before and after its serialization and deserialization.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeCollection.aml
================================================
This sample serializes a collection to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeConditionalProperty.aml
================================================
This sample uses a conditional property to exclude a property from serialization.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeContractResolver.aml
================================================
This sample uses a custom T:Newtonsoft.Json.Serialization.IContractResolver
to modify how objects are serialized.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeDataSet.aml
================================================
This sample serializes a T:System.Data.DataSet to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeDateFormatHandling.aml
================================================
This sample uses the T:Newtonsoft.Json.DateFormatHandling
setting to control how T:System.DateTime and T:System.DateTimeOffset are serialized.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeDateFormatString.aml
================================================
This sample uses the DateFormatString
setting to control how T:System.DateTime and T:System.DateTimeOffset are serialized.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeDateTimeZoneHandling.aml
================================================
This sample uses the T:Newtonsoft.Json.DateTimeZoneHandling
setting to control how T:System.DateTime and T:System.DateTimeOffset are serialized.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeDictionary.aml
================================================
This sample serializes a dictionary to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeExtensionData.aml
================================================
This sample serializes an object with extension data into JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeImmutableCollections.aml
================================================
This sample serializes an immutable collection into JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeObject.aml
================================================
This sample serializes an object to JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeRawJson.aml
================================================
This sample uses T:Newtonsoft.Json.Linq.JRaw
properties to serialize JSON with raw content.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeSerializationBinder.aml
================================================
This sample creates a custom T:System.Runtime.Serialization.SerializationBinder
that writes only the type name when including type data in JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeTypeNameHandling.aml
================================================
This sample uses the T:Newtonsoft.Json.TypeNameHandling
setting to include type information when serializing JSON and read type information so that the correct types are created when deserializing JSON.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeUnindentedJson.aml
================================================
This sample serializes an object to JSON without any formatting or indentation whitespace.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeWithJsonConverters.aml
================================================
This sample uses a T:Newtonsoft.Json.JsonConverter
to customize how JSON is serialized.Sample
================================================
FILE: Doc/Samples/Serializer/SerializeWithJsonSerializerToFile.aml
================================================
This sample serializes JSON to a file.Sample
================================================
FILE: Doc/Samples/Serializer/TraceWriter.aml
================================================
This sample uses an T:Newtonsoft.Json.Serialization.ITraceWriter
to log debug information from serialization.Sample
================================================
FILE: Doc/Samples/Xml/ConvertJsonToXml.aml
================================================
This sample converts JSON to XML.Sample
================================================
FILE: Doc/Samples/Xml/ConvertXmlToJson.aml
================================================
This sample converts XML to JSON.Sample
================================================
FILE: Doc/Samples/Xml/ConvertXmlToJsonForceArray.aml
================================================
This sample reads the json:Array="true" attribute in the XML and places its value in an array
when converting the XML to JSON.Sample
================================================
FILE: Doc/SelectToken.aml
================================================
Overload:Newtonsoft.Json.Linq.JToken.SelectToken
provides a method to query LINQ to JSON using a single string path to a desired
T:Newtonsoft.Json.Linq.JToken.
SelectToken makes dynamic queries easy because the entire query is defined in a string.SelectTokenSelectToken is a method on JToken and takes a string path to a child token.
SelectToken returns the child token or a null reference if a token couldn't be
found at the path's location.The path is made up of property names and array indexes separated by periods,
e.g. Manufacturers[0].Name.SelectToken with JSONPathSelectToken supports JSONPath queries. Find out more about JSONPath herehttps://goessner.net/articles/JsonPath/_blank.SelectToken with LINQSelectToken can be used in combination with standard LINQ methods.Overload:Newtonsoft.Json.Linq.JToken.SelectToken
================================================
FILE: Doc/SerializationAttributes.aml
================================================
Attributes can be used to control how Json.NET serializes and deserializes .NET objects.T:Newtonsoft.Json.JsonObjectAttribute - Placed on classes to control how they should be serialized as a JSON object.T:Newtonsoft.Json.JsonArrayAttribute - Placed on collections to control how they should be serialized as a JSON array.T:Newtonsoft.Json.JsonDictionaryAttribute - Placed on dictionaries to control how they should be serialized as a JSON object.T:Newtonsoft.Json.JsonPropertyAttribute - Placed on fields and properties to control how they should be serialized as a property in a JSON object.T:Newtonsoft.Json.JsonConverterAttribute - Placed on either classes or fields and properties to specify which JsonConverter should be used during serialization.T:Newtonsoft.Json.JsonExtensionDataAttribute - Placed on a collection field or property to deserialize properties with no matching class member into the specified collection and write values during serialization.T:Newtonsoft.Json.JsonConstructorAttribute - Placed on a constructor to specify that it should be used to create the class during deserialization.Standard .NET Serialization AttributesAs well as using the built-in Json.NET attributes, Json.NET also looks for the T:System.SerializableAttribute
(if IgnoreSerializableAttribute on DefaultContractResolver is set to false)
T:System.Runtime.Serialization.DataContractAttribute,
T:System.Runtime.Serialization.DataMemberAttribute,
and T:System.NonSerializedAttribute and attributes when determining how JSON is to be serialized and deserialized.
Json.NET attributes take precedence over standard .NET serialization attributes (e.g. if both JsonPropertyAttribute
and DataMemberAttribute are present on a property and both customize the name,
the name from JsonPropertyAttribute will be used).Json.NET Serialization AttributesJsonObjectAttributeThe MemberSerialization flag on this attribute specifies whether member serialization is opt-in
(a member must have the JsonProperty or DataMember attribute to be serialized), opt-out (everything is
serialized by default but can be ignored with the JsonIgnoreAttribute, Json.NET's default behavior) or
fields (all public and private fields are serialized and properties are ignored).Placing the the T:System.Runtime.Serialization.DataContractAttribute
on a type is another way to default member serialization to opt-in.The NamingStrategy setting on this attributes can be set to a T:Newtonsoft.Json.Serialization.NamingStrategy
type that specifies how property names are serialized.Json.NET serializes .NET classes that implement IEnumerable as a JSON array populated with the
IEnumerable values. Placing the T:Newtonsoft.Json.JsonObjectAttribute
overrides this behavior and forces the serializer to serialize the class's fields and properties.JsonArrayAttribute/JsonDictionaryAttributeThe T:Newtonsoft.Json.JsonArrayAttribute and
T:Newtonsoft.Json.JsonDictionaryAttribute are used to specify
whether a class is serialized as that collection type.The collection attributes have options to customize the JsonConverter, type name handling, and reference handling that are applied to collection items.JsonPropertyAttributeJsonPropertyAttribute has a number of uses:By default, the JSON property will have the same name as the .NET property. This attribute allows the name to be customized.JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in.It includes non-public properties in serialization and deserialization.It can be used to customize type name, reference, null, and default value handling for the property value.It can be used to customize the T:Newtonsoft.Json.Serialization.NamingStrategy of the serialized property name.It can be used to customize the property's collection items JsonConverter, type name handling, and reference handling. The DataMemberAttribute can be used as a substitute for JsonPropertyAttribute.JsonIgnoreAttributeExcludes a field or property from serialization.The T:System.NonSerializedAttribute can be used as a substitute for JsonIgnoreAttribute.JsonConverterAttributeThe T:Newtonsoft.Json.JsonConverterAttribute specifies which
T:Newtonsoft.Json.JsonConverter is used to convert an object.The attribute can be placed on a class or a member. When placed on a class, the JsonConverter
specified by the attribute will be the default way of serializing that class. When the attribute is
on a field or property, then the specified JsonConverter will always be used to serialize that value.The priority of which JsonConverter is used is member attribute, then class attribute, and finally
any converters passed to the JsonSerializer.This example shows the JsonConverterAttribute being applied to a property.To apply a JsonConverter to the items in a collection, use either T:Newtonsoft.Json.JsonArrayAttribute,
T:Newtonsoft.Json.JsonDictionaryAttribute or
T:Newtonsoft.Json.JsonPropertyAttribute
and set the ItemConverterType property to the converter type you want to use.JsonExtensionDataAttributeThe T:Newtonsoft.Json.JsonExtensionDataAttribute instructs the
T:Newtonsoft.Json.JsonSerializer to deserialize properties with no matching field or property
on the type into the specified collection. During serialization the values in this collection are written back to the instance's JSON object.All extension data values will be written during serialization, even if a property the same name has already been written.This example shows the JsonExtensionDataAttribute being applied to a field, unmatched JSON properties being added to the field's collection during deserialization.JsonConstructorAttributeThe T:Newtonsoft.Json.JsonConstructorAttribute instructs the
T:Newtonsoft.Json.JsonSerializer to use a specific constructor when deserializing a class. It can be used to create a class using a parameterized constructor instead of the default constructor, or to pick which specific parameterized constructor to use if there are multiple.T:Newtonsoft.Json.JsonObjectAttributeT:Newtonsoft.Json.JsonArrayAttributeT:Newtonsoft.Json.JsonDictionaryAttributeT:Newtonsoft.Json.JsonPropertyAttributeT:Newtonsoft.Json.JsonConverterAttributeT:Newtonsoft.Json.JsonExtensionDataAttributeT:Newtonsoft.Json.JsonConstructorAttribute
================================================
FILE: Doc/SerializationCallbacks.aml
================================================
Json.NET supports serialization callback methods. A callback can be used to manipulate an object before and after its serialization and deserialization by the JsonSerializer.OnSerializingOnSerializedOnDeserializingOnDeserialized
To tell the serializer which methods should be called during the object's
serialization lifecycle, decorate a method with the appropriate attribute
(T:System.Runtime.Serialization.OnSerializingAttribute,
T:System.Runtime.Serialization.OnSerializedAttribute,
T:System.Runtime.Serialization.OnDeserializingAttribute,
T:System.Runtime.Serialization.OnDeserializedAttribute).
ExampleExample object with serialization callback methods:The example object being serialized and deserialized by Json.NET:T:System.Runtime.Serialization.OnSerializingAttributeT:System.Runtime.Serialization.OnSerializedAttributeT:System.Runtime.Serialization.OnDeserializingAttributeT:System.Runtime.Serialization.OnDeserializedAttribute
================================================
FILE: Doc/SerializationErrorHandling.aml
================================================
Json.NET supports error handling during serialization and
deserialization. Error handling lets you catch an error and
choose whether to handle it and continue with serialization or
let the error bubble up and be thrown in your application.Error handling is defined through two methods: the E:Newtonsoft.Json.JsonSerializer.Error event on
JsonSerializer and the T:Newtonsoft.Json.Serialization.OnErrorAttribute.Error EventThe E:Newtonsoft.Json.JsonSerializer.Error
event is an event handler found on T:Newtonsoft.Json.JsonSerializer.
The error event is raised whenever an exception is thrown while serializing
or deserializing JSON. Like all settings found on JsonSerializer, it can also
be set on T:Newtonsoft.Json.JsonSerializerSettings
and passed to the serialization methods on JsonConvert.In this example we are deserializing a JSON array to a collection
of DateTimes. On the JsonSerializerSettings a handler has been assigned
to the Error event which will log the error message and mark the error
as handled.The result of deserializing the JSON is three successfully deserialized
dates and three error messages: one for the badly formatted string ("I am
not a date and will error!"), one for the nested JSON array, and one for the
null value since the list doesn't allow nullable DateTimes. The event
handler has logged these messages and Json.NET has continued on deserializing
the JSON because the errors were marked as handled.One thing to note with error handling in Json.NET is that an
unhandled error will bubble up and raise the event on each of its
parents. For example an unhandled error when serializing a collection of objects
will be raised twice, once against the object and then again on the collection.
This will let you handle an error either where it occurred or on one of its
parents.If you aren't immediately handling an error and only want to
perform an action against it once, then you can check to see whether the
T:Newtonsoft.Json.Serialization.ErrorEventArgs's
CurrentObject is equal to the OriginalObject.
OriginalObject is the object that threw the error and CurrentObject is
the object that the event is being raised against. They will only equal
the first time the event is raised against the OriginalObject.OnErrorAttributeThe T:Newtonsoft.Json.Serialization.OnErrorAttribute
works much like the other .NET serialization attributes
that Json.NET supports. To use it you simply place the
attribute on a method that takes the correct parameters: a
StreamingContext and an ErrorContext. The name of the method doesn't
matter.In this example accessing the Roles property will throw an
exception when no roles have been set. The HandleError method will set
the error when serializing Roles as handled and allow Json.NET to
continue serializing the class.E:Newtonsoft.Json.JsonSerializer.ErrorT:Newtonsoft.Json.Serialization.OnErrorAttribute
================================================
FILE: Doc/SerializationGuide.aml
================================================
The Json.NET serializer can serialize a wide variety of .NET objects. This guide looks at how it works, first at a high level and then in more detail.SummaryAt a high level, the Json.NET serializer will convert primitive .NET values into primitive JSON values,
will convert .NET arrays and collections to JSON arrays, and will convert everything else to JSON objects.Json.NET will throw an error if it encounters incorrect JSON when deserializing a value. For example, if
the serializer encounters a JSON property with an array of values and the type of matching .NET property is not
a collection, then an error will be thrown, and vice-versa.Complex Types
.NETJSONIList, IEnumerable, IList<T>, ArrayArray (properties on the collection will not be serialized)IDictionary, IDictionary<TKey, TValue>Object (dictionary name/values only, properties on the dictionary will not be serialized)Object (more detail below)Object
Primitive Types
.NETJSONStringStringByteSByteUInt16Int16UInt32Int32UInt64Int64IntegerFloatDoubleDecimalFloatEnumInteger (can be the enum value name with T:Newtonsoft.Json.Converters.StringEnumConverter)DateTimeString ()Byte[]String (base 64 encoded)TypeString (type name)GuidStringT:System.ComponentModel.TypeConverter (convertible to String)String
Breakdown of Type SerializationObjects.NET types that don't fall into any other category listed below
(i.e. aren't lists, dictionaries, dynamic, implement ISerializable, etc.)
are serialized as JSON objects. You can also force a type to be serialized as a JSON object by placing the
JsonObjectAttribute on the type.By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with
getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing
JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and
properties.Types can also be serialized using opt-in mode. Only properties and fields that have a JsonPropertyAttribute
or DataMemberAttribute on them will be serialized. Opt-in mode for an object is specified by placing the JsonObjectAttribute
or DataContractAttribute on the type.Finally, types can be serialized using a fields mode. All fields, both public and private, are serialized
and properties are ignored. This can be specified by setting MemberSerialization.Fields on a type with the JsonObjectAttribute
or by using the .NET T:System.SerializableAttribute
and setting IgnoreSerializableAttribute on DefaultContractResolver to false.IEnumerable, Lists, and Arrays .NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON
arrays only support a range of values and not properties, any additional properties and fields declared on .NET
collections are not serialized. In situations where a type implements IEnumerable but a JSON array is not wanted, then
the JsonObjectAttribute can be placed on the type to force it to be serialized as a JSON object instead.JsonArrayAttribute has options on it to customize the JsonConverter, type name handling, and reference handling
that are applied to collection items.Note that if TypeNameHandling or PreserveReferencesHandling has been enabled for JSON arrays on the serializer,
then JSON arrays are wrapped in a containing object. The object will have the type name/reference properties and a
$values property, which will have the collection data.When deserializing, if a member is typed as the interface IList<T>, then it will be deserialized as a
List<T>.You can read more about serializing collections here: Dictionaries and Hashtables.NET dictionaries (types that inherit from IDictionary) are converted to JSON objects. Note that only the
dictionary name/values will be written to the JSON object when serializing, and properties on the JSON object will
be added to the dictionary's name/values when deserializing. Additional members on the .NET dictionary are ignored
during serialization.When serializing a dictionary, the keys of the dictionary are converted to strings and used as the
JSON object property names. The string written for a key can be customized by either overriding
M:System.Object.ToString for the key type or by implementing a
T:System.ComponentModel.TypeConverter. A TypeConverter will also
support converting a custom string back again when deserializing a dictionary.JsonDictionaryAttribute has options on it to customize the JsonConverter, type name handling, and reference
handling that are applied to collection items.When deserializing, if a member is typed as the interface IDictionary<TKey, TValue> then it will be
deserialized as a Dictionary<TKey, TValue>.You can read more about serializing collections here: Untyped Objects.NET properties on a class that don't specify a type (i.e. they are just object) are serialized as usual. When
untyped properties are deserialized, the serializer has no way of knowing what type to create (unless type name handling
is enabled and the JSON contains the type names).For these untyped properties, the Json.NET serializer will read the JSON into LINQ to JSON objects and set them
to the property. JObject will be created for JSON objects; JArray will be created for JSON arrays, and JValue will be
created for primitive JSON values.DynamicThere are two different usages of dynamic (introduced in .NET 4) in .NET. The first are .NET properties with a
type of dynamic. Dynamic properties behave like properties declared as object: any value can be assigned to it, but
the difference being that properties and methods can be called on a dynamic property without casting. In Json.NET,
dynamic properties are serialized and deserialized exactly the same as untyped objects: because dynamic isn't an actual
type, Json.NET falls back to deserializing the JSON as LINQ to JSON objects.The second usage of dynamic in .NET are by the types that implement
T:System.Dynamic.IDynamicMetaObjectProvider. This interface lets
the implementer create dynamic objects that intercept the property and method calls on an object and use them.
T:System.Dynamic.ExpandoObject
is a good example of a dynamic object.Dynamic objects are serialized as JSON objects. A property is written for every member name returned by
M:System.Dynamic.DynamicMetaObject.GetDynamicMemberNames.
A dynamic object's normal properties aren't serialized by default but can be included by placing the
JsonPropertyAttribute on them.
When deserializing dynamic objects, the serializer first attempts to set JSON property values on a normal .NET
member with the matching name. If no .NET member is found with the property name, then the serializer will call
SetMember on the dynamic object. Because there is no type information for dynamic members on a dynamic object, the
values assigned to them will be LINQ to JSON objects.ISerializableTypes that implement T:System.Runtime.Serialization.ISerializable and
are marked with T:System.SerializableAttribute are serialized as JSON objects. When serializing, only the values returned from
ISerializable.GetObjectData are used; members on the type are ignored. When deserializing, the constructor with a
SerializationInfo and StreamingContext is called, passing the JSON object's values.In situations where this behavior is not wanted, the JsonObjectAttribute can be placed on a .NET type that
implements ISerializable to force it to be serialized as a normal JSON object.LINQ to JSONLINQ to JSON types (e.g. JObject and JArray) are automatically serialized and deserialized to their equivalent JSON
when encountered by the Json.NET serializer.JsonConverterSerialization of values that are convertible by a T:Newtonsoft.Json.JsonConverter
(i.e. CanConvert returns true for its type) is
completely overridden by the JsonConverter. The test to see whether a value can be converted by the JsonSerializer takes
precedence over all other tests.JsonConverters can be defined and specified in a number of places: in an attribute on a member, in an attribute
on a class, and added to the JsonSerializer's converters collection. The priority of which JsonConverter is used is the
JsonConverter defined by attribute on a member, then the JsonConverter defined by an attribute on a class, and finally
any converters passed to the JsonSerializer.Because a JsonConverter creates a new value, a converter will not work with readonly properties because there is no way to assign the new
value to the property. Either change the property to have a public setter or place a JsonPropertyAttribute or DataMemberAttribute on the property.T:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.JsonSerializerSettings
================================================
FILE: Doc/SerializationSettings.aml
================================================
JsonSerializer has a number of properties on it to customize how it serializes JSON. These can also be used
with the methods on JsonConvert via the T:Newtonsoft.Json.JsonSerializerSettings overloads.DateFormatHandlingT:Newtonsoft.Json.DateFormatHandling controls how dates are serialized.
MemberDescriptionIsoDateFormatBy default Json.NET writes dates in the ISO 8601 format, e.g. "2012-03-21T05:40Z".MicrosoftDateFormatDates are written in the Microsoft JSON format, e.g. "\/Date(1198908717056)\/".
MissingMemberHandlingT:Newtonsoft.Json.MissingMemberHandling controls how missing members, e.g. JSON contains a property that isn't a member on the object, are handled during deserialization.
MemberDescriptionIgnoreBy default Json.NET ignores JSON if there is no field or property for its value to be set to during deserialization.ErrorJson.NET errors when there is a missing member during deserialization.
ReferenceLoopHandlingT:Newtonsoft.Json.ReferenceLoopHandling controls how circular referencing objects,
e.g. a Person object referencing itself via a Manager property, are serialized.The M:System.Object.Equals(System.Object) method is used to test whether an object is in a circular reference.
By default Object.Equals(Object) will test whether the references are equal for reference types and private and public values
are equal for value types. Classes and structs can override this method.
MemberDescriptionErrorBy default Json.NET will error if a reference loop is encountered (otherwise the serializer will get into an infinite loop).IgnoreJson.NET will ignore objects in reference loops and not serialize them. The first time an object is encountered it will be serialized as usual but if the object is encountered as a child object of itself the serializer will skip serializing it.SerializeThis option forces Json.NET to serialize objects in reference loops. This is useful if objects are nested but not indefinitely.
ReferenceLoopHandling can be used as an argument when calling the serializer, it can be set on an object's properties or
a collection's items using P:Newtonsoft.Json.JsonContainerAttribute.ItemReferenceLoopHandling,
customized on a property with P:Newtonsoft.Json.JsonPropertyAttribute.ReferenceLoopHandling
or a property's object properties or collection items using
P:Newtonsoft.Json.JsonPropertyAttribute.ItemReferenceLoopHandling.NullValueHandlingT:Newtonsoft.Json.NullValueHandling controls how null values on .NET objects are handled during serialization and how null values in JSON are handled during deserialization.
MemberDescriptionIncludeBy default Json.NET writes null values to JSON when serializing and sets null values to fields/properties when deserializing.IgnoreJson.NET will skip writing JSON properties if the .NET value is null when serializing and will skip setting fields/properties if the JSON property is null when deserializing.
NullValueHandling can also be customized on individual properties with JsonPropertyAttribute.DefaultValueHandlingT:Newtonsoft.Json.DefaultValueHandling controls how Json.NET uses default values set using the .NET T:System.ComponentModel.DefaultValueAttribute when serializing and deserializing.
MemberDescriptionIncludeBy default Json.NET will write a field/property value to JSON when serializing if the value is the same as the field/property's default value.
The Json.NET deserializer will continue setting a field/property if the JSON value is the same as the default value.IgnoreJson.NET will skip writing a field/property value to JSON if the value is the same as the field/property's default value, or the custom
value specified in T:System.ComponentModel.DefaultValueAttribute if the attribute is present. The Json.NET deserializer
will skip setting a .NET object's field/property if the JSON value is the same as the default value.
DefaultValueHandling can also be customized on individual properties with JsonPropertyAttribute.ObjectCreationHandlingT:Newtonsoft.Json.ObjectCreationHandling controls how objects are created and deserialized to during deserialization.
MemberDescriptionAutoBy default Json.NET will attempt to set JSON values onto existing objects and add JSON values to existing collections during deserialization. ReuseSame behaviour as auto.ReplaceJson.NET will always recreate objects and collections before setting values to them during deserialization.
ObjectCreationHandling can also be customized on individual properties with JsonPropertyAttribute.TypeNameHandlingT:Newtonsoft.Json.TypeNameHandling should be used with caution when your application deserializes JSON from an external source.
Incoming types should be validated with a custom T:Newtonsoft.Json.Serialization.ISerializationBinder when deserializing with a value other than TypeNameHandling.None.
T:Newtonsoft.Json.TypeNameHandling controls whether Json.NET includes .NET type names
during serialization with a $type property and reads .NET type names from that property to determine what type to create during
deserialization.
Metadata properties like $type must be located at the beginning of a JSON object to be successfully detected during deserialization. If you can't control
the order of properties in your JSON object then T:Newtonsoft.Json.MetadataPropertyHandling can be used to remove this restriction.
The value of the $type property can be customized and validated by creating your own
T:Newtonsoft.Json.Serialization.ISerializationBinder.
MemberDescriptionNoneBy default Json.NET does not read or write type names during deserialization.ObjectsJson.NET will write and use type names for objects but not collections.ArraysJson.NET will write and use type names for collections but not objects.AutoJson.NET will check whether an object/collection matches its declared property and writes the type name if they do not match, e.g. a property with a type of Mammal has a derived instance of Dog assigned. Auto will ensure that type information isn't lost when serializing/deserializing automatically without having to write type names for every object.AllJson.NET will write and use type names for objects and collections.
TypeNameHandling can be used as an argument when calling the serializer, it can be set on an object's properties or
a collection's items using P:Newtonsoft.Json.JsonContainerAttribute.ItemTypeNameHandling,
customized on a property with P:Newtonsoft.Json.JsonPropertyAttribute.TypeNameHandling
or a property's object properties or collection items using
P:Newtonsoft.Json.JsonPropertyAttribute.ItemTypeNameHandling.TypeNameAssemblyFormatT:System.Runtime.Serialization.Formatters.FormatterAssemblyStyle controls how type names are written during serialization.
MemberDescriptionSimpleBy default Json.NET writes the partial assembly name with the type, e.g. System.Data.DataSet, System.Data. Note that Silverlight and Windows Phone are not able to use this format.FullJson.NET will write the full assembly name, including version number, culture and public key token.
Read more about the valid values at T:System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.SerializationBinderThe T:Newtonsoft.Json.Serialization.ISerializationBinder is used to resolve .NET types to type names during serialization and type names to .NET types during deserialization.
If TypeNameHandling is enabled then it is strongly recommended that a custom T:Newtonsoft.Json.Serialization.ISerializationBinder is used to validate incoming type names for security reasons.MetadataPropertyHandlingT:Newtonsoft.Json.MetadataPropertyHandling controls how metadata properties like $type and $id are read during deserialization.
For performance reasons by default the JsonSerializer assumes that any metadata properties are located at the beginning of a JSON object.
If you are unable to guarantee the order of properties in JSON you are deserializing then MetadataPropertyHandling.ReadAhead removes this
restriction at the cost of some performance.
MemberDescriptionDefaultBy default Json.NET will only read metadata properties that are at the beginning of a JSON object.ReadAheadJson.NET will look for metadata properties located anywhere in a JSON object.IgnoreJson.NET will ignore metadata properties.
ConstructorHandlingT:Newtonsoft.Json.ConstructorHandling controls how constructors are used when initializing objects during deserialization.
MemberDescriptionDefaultBy default Json.NET will first look for a constructor marked with the JsonConstructorAttribute, then look for a public default constructor
(a constructor that doesn't take any arguments), then check if the class has a single public constructor with arguments and finally check for a
non-public default constructor. If the class has multiple public constructors with arguments an error will be thrown. This can be fixed by
marking one of the constructors with the JsonConstructorAttribute.AllowNonPublicDefaultConstructorJson.NET will use a classes private default constructor before constructors with arguments if available.
ConvertersThis is the collection of JsonConverters that will be used during serialization and deserialization.A T:Newtonsoft.Json.JsonConverter allows JSON to be manually written during serialization and read during deserialization.
This is useful for particularly complex JSON structures or for when you want to change how a type is serialized.When a JsonConverter has been added to a JsonSerializer it will be checked for every value that is being serialized/deserialized
using its CanConvert to see if it should be used. If CanConvert returns true then the JsonConverter will be used to read or write
the JSON for that value. Note that while a JsonConverter gives you complete control over that values JSON, many Json.NET serialization
features are no longer available like type name and reference handling.JsonConverters can be used as an argument when calling the serializer, it can be set on an object or property
using T:Newtonsoft.Json.JsonConverterAttribute, it be set on an object's properties or
a collection's items using P:Newtonsoft.Json.JsonContainerAttribute.ItemConverterType,
or a property's object properties or collection items using
P:Newtonsoft.Json.JsonPropertyAttribute.ItemConverterType.To create your own custom converter inherit from the JsonConverter class. Read more about the built-in JsonConverters below:T:Newtonsoft.Json.Converters.StringEnumConverterContractResolverInternally for every .NET type the JsonSerializer will create a contract of how the type should be serialized and deserialized,
based on type metadata and attributes applied to the class. Specifying a custom T:Newtonsoft.Json.Serialization.IContractResolver
allows the creation of contracts to be customized.Read more about Contract Resolvers here: TraceWriterThe Json.NET serializer supports logging and debugging using the
T:Newtonsoft.Json.Serialization.ITraceWriter interface.
By assigning a trace writer you can debug what happens inside the Json.NET serializer when serializing and deserializing JSON.Read more about TraceWriters here: ErrorThe E:Newtonsoft.Json.JsonSerializer.Error event can catch errors during serialization and either handle the event and continue with
serialization or let the error bubble up and be thrown to the application.Read more about error handling here: T:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.JsonSerializerSettingsT:Newtonsoft.Json.JsonConverterT:System.Runtime.Serialization.SerializationBinder
================================================
FILE: Doc/SerializationTracing.aml
================================================
The Json.NET serializer supports logging and debugging using the
T:Newtonsoft.Json.Serialization.ITraceWriter interface.
By assigning a trace writer you can capture serialization messages and errors and debug what happens inside the
Json.NET serializer when serializing and deserializing JSON.ITraceWriterA trace writer can be assigned using properties on JsonSerializerSettings or JsonSerializer.Json.NET has two implementations of ITraceWriter: T:Newtonsoft.Json.Serialization.MemoryTraceWriter,
which keeps messages in memory for simple debugging, like the example
above, and T:Newtonsoft.Json.Serialization.DiagnosticsTraceWriter, which writes messages to any
System.Diagnostics.TraceListeners your application is using.Custom ITraceWriterTo write messages using your existing logging framework, just implement a custom version of ITraceWriter.T:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.Serialization.ITraceWriterT:Newtonsoft.Json.Serialization.MemoryTraceWriterT:Newtonsoft.Json.Serialization.DiagnosticsTraceWriter
================================================
FILE: Doc/SerializingCollections.aml
================================================
Json.NET has excellent support for serializing and deserializing
collections of objects.Serializing CollectionsTo serialize a collection - a generic list, array, dictionary, or
your own custom collection - simply call the serializer with the object
you want to get JSON for. Json.NET will serialize the collection and all
of the values it contains.Deserializing CollectionsTo deserialize JSON into a .NET collection, just specify the collection
type you want to deserialize to. Json.NET supports a wide range of collection
types.Deserializing DictionariesUsing Json.NET you can also deserialize a JSON object into a .NET
generic dictionary. The JSON object's property names and values will be
added to the dictionary.T:Newtonsoft.Json.JsonConvertT:Newtonsoft.Json.JsonSerializer
================================================
FILE: Doc/SerializingJSON.aml
================================================
The quickest method of converting between JSON text and a .NET object is using the
T:Newtonsoft.Json.JsonSerializer.
The JsonSerializer converts .NET objects into their JSON equivalent and back again by mapping the .NET object property names to the JSON property names
and copies the values for you.JsonConvertFor simple scenarios where you want to convert to and from a JSON string, the
Overload:Newtonsoft.Json.JsonConvert.SerializeObject and
Overload:Newtonsoft.Json.JsonConvert.DeserializeObject
methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer.
SerializeObject and DeserializeObject both have overloads that take a T:Newtonsoft.Json.JsonSerializerSettings object.
JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods.
JsonSerializerFor more control over how an object is serialized, the T:Newtonsoft.Json.JsonSerializer can be used directly.
The JsonSerializer is able to read and write JSON text directly to a stream via T:Newtonsoft.Json.JsonTextReader
and T:Newtonsoft.Json.JsonTextWriter.
Other kinds of JsonWriters can also be used, such as
T:Newtonsoft.Json.Linq.JTokenReader/T:Newtonsoft.Json.Linq.JTokenWriter,
to convert your object to and from LINQ to JSON objects, or
T:Newtonsoft.Json.Bson.BsonReader/T:Newtonsoft.Json.Bson.BsonWriter, to convert to and from BSON.JsonSerializer has a number of properties on it to customize how it serializes JSON. These can also be used with the methods on JsonConvert via the JsonSerializerSettings overloads.You can read more about the available JsonSerializer settings here: T:Newtonsoft.Json.JsonConvertT:Newtonsoft.Json.JsonSerializerT:Newtonsoft.Json.JsonSerializerSettings
================================================
FILE: Doc/SerializingJSONFragments.aml
================================================
Often when working with large JSON documents you're only interested in a small
fragment of information. This scenario can be annoying when you want to deserialize
that JSON fragment into .NET objects because you have to define .NET classes for the
entire JSON result.With Json.NET it is easy to get around this problem. Using LINQ to JSON you
can extract the pieces of JSON you want to deserialize before passing them to the
Json.NET serializer.T:Newtonsoft.Json.JsonReaderT:Newtonsoft.Json.JsonWriterT:Newtonsoft.Json.Linq.JTokenReaderT:Newtonsoft.Json.Linq.JTokenWriterT:Newtonsoft.Json.Bson.BsonReaderT:Newtonsoft.Json.Bson.BsonWriter
================================================
FILE: Doc/doc.content
================================================
================================================
FILE: Doc/doc.shfbproj
================================================
DebugAnyCPU2.0{fd19f68e-72c8-4576-9775-b4480b0db686}2017.9.26.0DocumentationDocumentationDocumentation..\Working\Documentation\DocumentationSummary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter, AutoDocumentDisposeInheritedMembers, InheritedFrameworkMembers, Protected, SealedProtected, ProtectedInternalAsProtected, EditorBrowsableNever, NonBrowsableWebsite.NET Framework 4.5Json.NET DocumentationVS2013MemberName..\Working\Src\Newtonsoft.Json\bin\Release\Net45The <b>Newtonsoft.Json</b> namespace provides classes that are used to implement the core services of the framework.The <b>Newtonsoft.Json.Converters</b> namespace provides classes that inherit from <a href="T_Newtonsoft_Json_JsonConverter.htm">JsonConverter</a>.The <b>Newtonsoft.Json.Linq</b> namespace provides classes that are used to implement LINQ to JSON.The <b>Newtonsoft.Json.Linq.ComponentModel</b> namespace provides classes for LINQ to JSON databinding.<para>The <b>Newtonsoft.Json.Schema</b> namespace provides classes that are used to implement JSON schema.</para>
<para><b>Obsolete.</b> JSON Schema validation has been moved to its own package. See <a href="https://www.newtonsoft.com/jsonschema">https://www.newtonsoft.com/jsonschema</a> for more details.</para>The <b>Newtonsoft.Json.Linq</b> namespace provides classes that are used when serializing and deserializing JSON.The <b>Newtonsoft.Json.Linq</b> namespace provides classes that are used to implement BSON.TrueAPI Reference{@HelpFormatOutputPaths}FalseOnlyWarningsAndErrorsTrueFalseFalseTrueC#BlankFalseen-USAboveNamespaces2False<%3ba href="%3b../../"%3b>%3bJson.NET Home<%3b/a>%3bticktickcrosscrossperformanceperformancelogologo
================================================
FILE: Doc/license.txt
================================================
Copyright (c) 2007 James Newton-King
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: Doc/readme.txt
================================================
Json.NET
https://www.newtonsoft.com/json
https://github.com/JamesNK/Newtonsoft.Json
Description:
Json.NET is a popular high-performance JSON framework for .NET
-Flexible JSON serializer for converting between .NET objects and JSON
-LINQ to JSON for manually reading and writing JSON
-High performance, faster than .NET's built-in JSON serializers
-Write indented, easy to read JSON
-Convert JSON to and from XML
-Supports .NET 2, .NET 3.5, .NET 4, .NET 4.5, Silverlight, Windows Phone, Windows 8 Store and .NET Core
Documentation:
https://www.newtonsoft.com/json/help/
Versions:
Json.NET has different libraries for the various .NET Framework versions.
-net45:
.NET 4.5+
-net40:
.NET 4.0
-net35:
.NET 3.5
-net20:
.NET 2.0, Unity
-portable-net45+win8+wpa81+wp8:
.NET 4.5, Windows Phone 8, Windows 8 Store
-portable-net40+win8+wpa81+wp8+sl5:
.NET 4.0, Windows Phone 8, Windows 8 Store, Silverlight 5, MonoTouch, MonoDroid
-netstandard1.0:
.NET Standard 1.0
-netstandard1.3:
.NET Standard 1.3
-netstandard2.0:
.NET Standard 2.0
Notes:
For a Compact Framework 3.5 and Silverlight 3.0 builds download Json.NET 3.5
For a Silverlight 4.0 and Windows Phone 7 builds download Json.NET 5
================================================
FILE: ISSUE_TEMPLATE.md
================================================
### Source/destination types
```csharp
// Put the types you are serializing or deserializing here
```
### Source/destination JSON
```javascript
{"message":"Place your serialized or deserialized JSON here"}
```
### Expected behavior
### Actual behavior
### Steps to reproduce
```csharp
// Your calls to Newtonsoft.Json here
```
================================================
FILE: LICENSE.md
================================================
The MIT License (MIT)
Copyright (c) 2007 James Newton-King
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
#  Json.NET
[](https://www.nuget.org/packages/Newtonsoft.Json/)
[](https://dev.azure.com/jamesnk/Public/_build/latest?definitionId=8)
- [Homepage](https://www.newtonsoft.com/json)
- [Documentation](https://www.newtonsoft.com/json/help)
- [NuGet Package](https://www.nuget.org/packages/Newtonsoft.Json)
- [Release Notes](https://github.com/JamesNK/Newtonsoft.Json/releases)
- [Contributing Guidelines](CONTRIBUTING.md)
- [License](LICENSE.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/json.net)
================================================
FILE: Src/Directory.Build.props
================================================
4.6.20.10.104.2.38.0.04.3.01.0.016.3.04.8.13.11.03.13.04.4.01.4.04.3.04.3.04.3.04.3.04.3.04.3.04.4.02.3.12.3.1
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonBinaryType.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonBinaryType : byte
{
Binary = 0x00,
Function = 0x01,
[Obsolete("This type has been deprecated in the BSON specification. Use Binary instead.")]
BinaryOld = 0x02,
[Obsolete("This type has been deprecated in the BSON specification. Use Uuid instead.")]
UuidOld = 0x03,
Uuid = 0x04,
Md5 = 0x05,
UserDefined = 0x80
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal class BsonBinaryWriter
{
private static readonly Encoding Encoding = new UTF8Encoding(false);
private readonly BinaryWriter _writer;
private byte[] _largeByteBuffer;
public DateTimeKind DateTimeKindHandling { get; set; }
public BsonBinaryWriter(BinaryWriter writer)
{
DateTimeKindHandling = DateTimeKind.Utc;
_writer = writer;
}
public void Flush()
{
_writer.Flush();
}
public void Close()
{
#if HAVE_STREAM_READER_WRITER_CLOSE
_writer.Close();
#else
_writer.Dispose();
#endif
}
public void WriteToken(BsonToken t)
{
CalculateSize(t);
WriteTokenInternal(t);
}
private void WriteTokenInternal(BsonToken t)
{
switch (t.Type)
{
case BsonType.Object:
{
BsonObject value = (BsonObject)t;
_writer.Write(value.CalculatedSize);
foreach (BsonProperty property in value)
{
_writer.Write((sbyte)property.Value.Type);
WriteString((string)property.Name.Value, property.Name.ByteCount, null);
WriteTokenInternal(property.Value);
}
_writer.Write((byte)0);
}
break;
case BsonType.Array:
{
BsonArray value = (BsonArray)t;
_writer.Write(value.CalculatedSize);
ulong index = 0;
foreach (BsonToken c in value)
{
_writer.Write((sbyte)c.Type);
WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
WriteTokenInternal(c);
index++;
}
_writer.Write((byte)0);
}
break;
case BsonType.Integer:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Long:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.String:
{
BsonString value = (BsonString)t;
WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
}
break;
case BsonType.Boolean:
_writer.Write(t == BsonBoolean.True);
break;
case BsonType.Null:
case BsonType.Undefined:
break;
case BsonType.Date:
{
BsonValue value = (BsonValue)t;
long ticks = 0;
if (value.Value is DateTime dateTime)
{
if (DateTimeKindHandling == DateTimeKind.Utc)
{
dateTime = dateTime.ToUniversalTime();
}
else if (DateTimeKindHandling == DateTimeKind.Local)
{
dateTime = dateTime.ToLocalTime();
}
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
}
#if HAVE_DATE_TIME_OFFSET
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
}
#endif
_writer.Write(ticks);
}
break;
case BsonType.Binary:
{
BsonBinary value = (BsonBinary)t;
byte[] data = (byte[])value.Value;
_writer.Write(data.Length);
_writer.Write((byte)value.BinaryType);
_writer.Write(data);
}
break;
case BsonType.Oid:
{
BsonValue value = (BsonValue)t;
byte[] data = (byte[])value.Value;
_writer.Write(data);
}
break;
case BsonType.Regex:
{
BsonRegex value = (BsonRegex)t;
WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
WriteString((string)value.Options.Value, value.Options.ByteCount, null);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
}
}
private void WriteString(string s, int byteCount, int? calculatedlengthPrefix)
{
if (calculatedlengthPrefix != null)
{
_writer.Write(calculatedlengthPrefix.GetValueOrDefault());
}
WriteUtf8Bytes(s, byteCount);
_writer.Write((byte)0);
}
public void WriteUtf8Bytes(string s, int byteCount)
{
if (s != null)
{
if (byteCount <= 256)
{
if (_largeByteBuffer == null)
{
_largeByteBuffer = new byte[256];
}
Encoding.GetBytes(s, 0, s.Length, _largeByteBuffer, 0);
_writer.Write(_largeByteBuffer, 0, byteCount);
}
else
{
byte[] bytes = Encoding.GetBytes(s);
_writer.Write(bytes);
}
}
}
private int CalculateSize(int stringByteCount)
{
return stringByteCount + 1;
}
private int CalculateSizeWithLength(int stringByteCount, bool includeSize)
{
int baseSize = (includeSize)
? 5 // size bytes + terminator
: 1; // terminator
return baseSize + stringByteCount;
}
private int CalculateSize(BsonToken t)
{
switch (t.Type)
{
case BsonType.Object:
{
BsonObject value = (BsonObject)t;
int bases = 4;
foreach (BsonProperty p in value)
{
int size = 1;
size += CalculateSize(p.Name);
size += CalculateSize(p.Value);
bases += size;
}
bases += 1;
value.CalculatedSize = bases;
return bases;
}
case BsonType.Array:
{
BsonArray value = (BsonArray)t;
int size = 4;
ulong index = 0;
foreach (BsonToken c in value)
{
size += 1;
size += CalculateSize(MathUtils.IntLength(index));
size += CalculateSize(c);
index++;
}
size += 1;
value.CalculatedSize = size;
return value.CalculatedSize;
}
case BsonType.Integer:
return 4;
case BsonType.Long:
return 8;
case BsonType.Number:
return 8;
case BsonType.String:
{
BsonString value = (BsonString)t;
string s = (string)value.Value;
value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0;
value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength);
return value.CalculatedSize;
}
case BsonType.Boolean:
return 1;
case BsonType.Null:
case BsonType.Undefined:
return 0;
case BsonType.Date:
return 8;
case BsonType.Binary:
{
BsonBinary value = (BsonBinary)t;
byte[] data = (byte[])value.Value;
value.CalculatedSize = 4 + 1 + data.Length;
return value.CalculatedSize;
}
case BsonType.Oid:
return 12;
case BsonType.Regex:
{
BsonRegex value = (BsonRegex)t;
int size = 0;
size += CalculateSize(value.Pattern);
size += CalculateSize(value.Options);
value.CalculatedSize = size;
return value.CalculatedSize;
}
default:
throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
}
}
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonObjectId.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
///
/// Represents a BSON Oid (object id).
///
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonObjectId
{
///
/// Gets or sets the value of the Oid.
///
/// The value of the Oid.
public byte[] Value { get; }
///
/// Initializes a new instance of the class.
///
/// The Oid value.
public BsonObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value.Length != 12)
{
throw new ArgumentException("An ObjectId must be 12 bytes", nameof(value));
}
Value = value;
}
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonReader.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
#nullable disable
namespace Newtonsoft.Json.Bson
{
///
/// Represents a reader that provides fast, non-cached, forward-only access to serialized BSON data.
///
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonReader : JsonReader
{
private const int MaxCharBytesSize = 128;
private static readonly byte[] SeqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence
private static readonly byte[] SeqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence
private static readonly byte[] SeqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence
private static readonly byte[] SeqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence
private readonly BinaryReader _reader;
private readonly List _stack;
private byte[] _byteBuffer;
private char[] _charBuffer;
private BsonType _currentElementType;
private BsonReaderState _bsonReaderState;
private ContainerContext _currentContext;
private bool _readRootValueAsArray;
private bool _jsonNet35BinaryCompatibility;
private DateTimeKind _dateTimeKindHandling;
private enum BsonReaderState
{
Normal = 0,
ReferenceStart = 1,
ReferenceRef = 2,
ReferenceId = 3,
CodeWScopeStart = 4,
CodeWScopeCode = 5,
CodeWScopeScope = 6,
CodeWScopeScopeObject = 7,
CodeWScopeScopeEnd = 8
}
private class ContainerContext
{
public readonly BsonType Type;
public int Length;
public int Position;
public ContainerContext(BsonType type)
{
Type = type;
}
}
///
/// Gets or sets a value indicating whether binary data reading should be compatible with incorrect Json.NET 3.5 written binary.
///
///
/// true if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, false.
///
[Obsolete("JsonNet35BinaryCompatibility will be removed in a future version of Json.NET.")]
public bool JsonNet35BinaryCompatibility
{
get => _jsonNet35BinaryCompatibility;
set => _jsonNet35BinaryCompatibility = value;
}
///
/// Gets or sets a value indicating whether the root object will be read as a JSON array.
///
///
/// true if the root object will be read as a JSON array; otherwise, false.
///
public bool ReadRootValueAsArray
{
get => _readRootValueAsArray;
set => _readRootValueAsArray = value;
}
///
/// Gets or sets the used when reading values from BSON.
///
/// The used when reading values from BSON.
public DateTimeKind DateTimeKindHandling
{
get => _dateTimeKindHandling;
set => _dateTimeKindHandling = value;
}
///
/// Initializes a new instance of the class.
///
/// The containing the BSON data to read.
public BsonReader(Stream stream)
: this(stream, false, DateTimeKind.Local)
{
}
///
/// Initializes a new instance of the class.
///
/// The containing the BSON data to read.
public BsonReader(BinaryReader reader)
: this(reader, false, DateTimeKind.Local)
{
}
///
/// Initializes a new instance of the class.
///
/// The containing the BSON data to read.
/// if set to true the root object will be read as a JSON array.
/// The used when reading values from BSON.
public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(stream, nameof(stream));
_reader = new BinaryReader(stream);
_stack = new List();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
///
/// Initializes a new instance of the class.
///
/// The containing the BSON data to read.
/// if set to true the root object will be read as a JSON array.
/// The used when reading values from BSON.
public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
_reader = reader;
_stack = new List();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
private string ReadElement()
{
_currentElementType = ReadType();
string elementName = ReadString();
return elementName;
}
///
/// Reads the next JSON token from the underlying .
///
///
/// true if the next token was read successfully; false if there are no more tokens to read.
///
public override bool Read()
{
try
{
bool success;
switch (_bsonReaderState)
{
case BsonReaderState.Normal:
success = ReadNormal();
break;
case BsonReaderState.ReferenceStart:
case BsonReaderState.ReferenceRef:
case BsonReaderState.ReferenceId:
success = ReadReference();
break;
case BsonReaderState.CodeWScopeStart:
case BsonReaderState.CodeWScopeCode:
case BsonReaderState.CodeWScopeScope:
case BsonReaderState.CodeWScopeScopeObject:
case BsonReaderState.CodeWScopeScopeEnd:
success = ReadCodeWScope();
break;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
}
if (!success)
{
SetToken(JsonToken.None);
return false;
}
return true;
}
catch (EndOfStreamException)
{
SetToken(JsonToken.None);
return false;
}
}
///
/// Changes the reader's state to .
/// If is set to true, the underlying is also closed.
///
public override void Close()
{
base.Close();
if (CloseInput)
{
#if HAVE_STREAM_READER_WRITER_CLOSE
_reader?.Close();
#else
_reader?.Dispose();
#endif
}
}
private bool ReadCodeWScope()
{
switch (_bsonReaderState)
{
case BsonReaderState.CodeWScopeStart:
SetToken(JsonToken.PropertyName, "$code");
_bsonReaderState = BsonReaderState.CodeWScopeCode;
return true;
case BsonReaderState.CodeWScopeCode:
// total CodeWScope size - not used
ReadInt32();
SetToken(JsonToken.String, ReadLengthString());
_bsonReaderState = BsonReaderState.CodeWScopeScope;
return true;
case BsonReaderState.CodeWScopeScope:
if (CurrentState == State.PostValue)
{
SetToken(JsonToken.PropertyName, "$scope");
return true;
}
else
{
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case BsonReaderState.CodeWScopeScopeObject:
bool result = ReadNormal();
if (result && TokenType == JsonToken.EndObject)
{
_bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
}
return result;
case BsonReaderState.CodeWScopeScopeEnd:
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool ReadReference()
{
switch (CurrentState)
{
case State.ObjectStart:
{
SetToken(JsonToken.PropertyName, JsonTypeReflector.RefPropertyName);
_bsonReaderState = BsonReaderState.ReferenceRef;
return true;
}
case State.Property:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.String, ReadLengthString());
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.Bytes, ReadBytes(12));
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
case State.PostValue:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.PropertyName, JsonTypeReflector.IdPropertyName);
_bsonReaderState = BsonReaderState.ReferenceId;
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
default:
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState);
}
}
private bool ReadNormal()
{
switch (CurrentState)
{
case State.Start:
{
JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
SetToken(token);
ContainerContext newContext = new ContainerContext(type);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case State.Complete:
case State.Closed:
return false;
case State.Property:
{
ReadType(_currentElementType);
return true;
}
case State.ObjectStart:
case State.ArrayStart:
case State.PostValue:
ContainerContext context = _currentContext;
if (context == null)
{
if (SupportMultipleContent)
{
goto case State.Start;
}
return false;
}
int lengthMinusEnd = context.Length - 1;
if (context.Position < lengthMinusEnd)
{
if (context.Type == BsonType.Array)
{
ReadElement();
ReadType(_currentElementType);
return true;
}
else
{
SetToken(JsonToken.PropertyName, ReadElement());
return true;
}
}
else if (context.Position == lengthMinusEnd)
{
if (ReadByte() != 0)
{
throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
}
PopContext();
if (_currentContext != null)
{
MovePosition(context.Length);
}
JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
SetToken(endToken);
return true;
}
else
{
throw JsonReaderException.Create(this, "Read past end of current container context.");
}
case State.ConstructorStart:
break;
case State.Constructor:
break;
case State.Error:
break;
case State.Finished:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private void PopContext()
{
_stack.RemoveAt(_stack.Count - 1);
if (_stack.Count == 0)
{
_currentContext = null;
}
else
{
_currentContext = _stack[_stack.Count - 1];
}
}
private void PushContext(ContainerContext newContext)
{
_stack.Add(newContext);
_currentContext = newContext;
}
private byte ReadByte()
{
MovePosition(1);
return _reader.ReadByte();
}
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
double d = ReadDouble();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
}
else
{
SetToken(JsonToken.Float, d);
}
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
BsonBinaryType binaryType;
byte[] data = ReadBinary(out binaryType);
object value = (binaryType != BsonBinaryType.Uuid)
? data
: (object)new Guid(data);
SetToken(JsonToken.Bytes, value);
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long)ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
}
}
private byte[] ReadBinary(out BsonBinaryType binaryType)
{
int dataLength = ReadInt32();
binaryType = (BsonBinaryType)ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility)
{
dataLength = ReadInt32();
}
#pragma warning restore 612,618
return ReadBytes(dataLength);
}
private string ReadString()
{
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
while (true)
{
int count = offset;
byte b;
while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
{
_byteBuffer[count++] = b;
}
int byteCount = count - offset;
totalBytesRead += byteCount;
if (count < MaxCharBytesSize && builder == null)
{
// pref optimization to avoid reading into a string builder
// if string is smaller than the buffer then return it directly
int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
MovePosition(totalBytesRead + 1);
return new string(_charBuffer, 0, length);
}
else
{
// calculate the index of the end of the last full character in the buffer
int lastFullCharStop = GetLastFullCharStop(count - 1);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
if (builder == null)
{
builder = new StringBuilder(MaxCharBytesSize * 2);
}
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
// reached end of string
if (count < MaxCharBytesSize)
{
MovePosition(totalBytesRead + 1);
return builder.ToString();
}
offset = 0;
}
}
}
}
private string ReadLengthString()
{
int length = ReadInt32();
MovePosition(length);
string s = GetString(length - 1);
_reader.ReadByte();
return s;
}
private string GetString(int length)
{
if (length == 0)
{
return string.Empty;
}
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
? MaxCharBytesSize - offset
: length - totalBytesRead;
int byteCount = _reader.Read(_byteBuffer, offset, count);
if (byteCount == 0)
{
throw new EndOfStreamException("Unable to read beyond the end of the stream.");
}
totalBytesRead += byteCount;
// Above, byteCount is how many bytes we read this time.
// Below, byteCount is how many bytes are in the _byteBuffer.
byteCount += offset;
if (byteCount == length)
{
// pref optimization to avoid reading into a string builder
// first iteration and all bytes read then return string directly
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
return new string(_charBuffer, 0, charCount);
}
else
{
int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
if (builder == null)
{
builder = new StringBuilder(length);
}
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
offset = 0;
}
}
} while (totalBytesRead < length);
return builder.ToString();
}
private int GetLastFullCharStop(int start)
{
int lookbackPos = start;
int bis = 0;
while (lookbackPos >= 0)
{
bis = BytesInSequence(_byteBuffer[lookbackPos]);
if (bis == 0)
{
lookbackPos--;
continue;
}
else if (bis == 1)
{
break;
}
else
{
lookbackPos--;
break;
}
}
if (bis == start - lookbackPos)
{
//Full character.
return start;
}
else
{
return lookbackPos;
}
}
private int BytesInSequence(byte b)
{
if (b <= SeqRange1[1])
{
return 1;
}
if (b >= SeqRange2[0] && b <= SeqRange2[1])
{
return 2;
}
if (b >= SeqRange3[0] && b <= SeqRange3[1])
{
return 3;
}
if (b >= SeqRange4[0] && b <= SeqRange4[1])
{
return 4;
}
return 0;
}
private void EnsureBuffers()
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
_charBuffer = new char[charBufferSize];
}
}
private double ReadDouble()
{
MovePosition(8);
return _reader.ReadDouble();
}
private int ReadInt32()
{
MovePosition(4);
return _reader.ReadInt32();
}
private long ReadInt64()
{
MovePosition(8);
return _reader.ReadInt64();
}
private BsonType ReadType()
{
MovePosition(1);
return (BsonType)_reader.ReadSByte();
}
private void MovePosition(int count)
{
_currentContext.Position += count;
}
private byte[] ReadBytes(int count)
{
MovePosition(count);
return _reader.ReadBytes(count);
}
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonToken.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections;
using System.Collections.Generic;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal abstract class BsonToken
{
public abstract BsonType Type { get; }
public BsonToken Parent { get; set; }
public int CalculatedSize { get; set; }
}
internal class BsonObject : BsonToken, IEnumerable
{
private readonly List _children = new List();
public void Add(string name, BsonToken token)
{
_children.Add(new BsonProperty { Name = new BsonString(name, false), Value = token });
token.Parent = this;
}
public override BsonType Type => BsonType.Object;
public IEnumerator GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class BsonArray : BsonToken, IEnumerable
{
private readonly List _children = new List();
public void Add(BsonToken token)
{
_children.Add(token);
token.Parent = this;
}
public override BsonType Type => BsonType.Array;
public IEnumerator GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class BsonEmpty : BsonToken
{
public static readonly BsonToken Null = new BsonEmpty(BsonType.Null);
public static readonly BsonToken Undefined = new BsonEmpty(BsonType.Undefined);
private BsonEmpty(BsonType type)
{
Type = type;
}
public override BsonType Type { get; }
}
internal class BsonValue : BsonToken
{
private readonly object _value;
private readonly BsonType _type;
public BsonValue(object value, BsonType type)
{
_value = value;
_type = type;
}
public object Value => _value;
public override BsonType Type => _type;
}
internal class BsonBoolean : BsonValue
{
public static readonly BsonBoolean False = new BsonBoolean(false);
public static readonly BsonBoolean True = new BsonBoolean(true);
private BsonBoolean(bool value)
: base(value, BsonType.Boolean)
{
}
}
internal class BsonString : BsonValue
{
public int ByteCount { get; set; }
public bool IncludeLength { get; }
public BsonString(object value, bool includeLength)
: base(value, BsonType.String)
{
IncludeLength = includeLength;
}
}
internal class BsonBinary : BsonValue
{
public BsonBinaryType BinaryType { get; set; }
public BsonBinary(byte[] value, BsonBinaryType binaryType)
: base(value, BsonType.Binary)
{
BinaryType = binaryType;
}
}
internal class BsonRegex : BsonToken
{
public BsonString Pattern { get; set; }
public BsonString Options { get; set; }
public BsonRegex(string pattern, string options)
{
Pattern = new BsonString(pattern, false);
Options = new BsonString(options, false);
}
public override BsonType Type => BsonType.Regex;
}
internal class BsonProperty
{
public BsonString Name { get; set; }
public BsonToken Value { get; set; }
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonType.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonType : sbyte
{
Number = 1,
String = 2,
Object = 3,
Array = 4,
Binary = 5,
Undefined = 6,
Oid = 7,
Boolean = 8,
Date = 9,
Null = 10,
Regex = 11,
Reference = 12,
Code = 13,
Symbol = 14,
CodeWScope = 15,
Integer = 16,
TimeStamp = 17,
Long = 18,
MinKey = -1,
MaxKey = 127
}
}
================================================
FILE: Src/Newtonsoft.Json/Bson/BsonWriter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
#nullable disable
namespace Newtonsoft.Json.Bson
{
///
/// Represents a writer that provides a fast, non-cached, forward-only way of generating BSON data.
///
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonWriter : JsonWriter
{
private readonly BsonBinaryWriter _writer;
private BsonToken _root;
private BsonToken _parent;
private string _propertyName;
///
/// Gets or sets the used when writing values to BSON.
/// When set to no conversion will occur.
///
/// The used when writing values to BSON.
public DateTimeKind DateTimeKindHandling
{
get => _writer.DateTimeKindHandling;
set => _writer.DateTimeKindHandling = value;
}
///
/// Initializes a new instance of the class.
///
/// The to write to.
public BsonWriter(Stream stream)
{
ValidationUtils.ArgumentNotNull(stream, nameof(stream));
_writer = new BsonBinaryWriter(new BinaryWriter(stream));
}
///
/// Initializes a new instance of the class.
///
/// The to write to.
public BsonWriter(BinaryWriter writer)
{
ValidationUtils.ArgumentNotNull(writer, nameof(writer));
_writer = new BsonBinaryWriter(writer);
}
///
/// Flushes whatever is in the buffer to the underlying and also flushes the underlying stream.
///
public override void Flush()
{
_writer.Flush();
}
///
/// Writes the end.
///
/// The token.
protected override void WriteEnd(JsonToken token)
{
base.WriteEnd(token);
RemoveParent();
if (Top == 0)
{
_writer.WriteToken(_root);
}
}
///
/// Writes a comment /*...*/ containing the specified text.
///
/// Text to place inside the comment.
public override void WriteComment(string text)
{
throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null);
}
///
/// Writes the start of a constructor with the given name.
///
/// The name of the constructor.
public override void WriteStartConstructor(string name)
{
throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null);
}
///
/// Writes raw JSON.
///
/// The raw JSON to write.
public override void WriteRaw(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
///
/// Writes raw JSON where a value is expected and updates the writer's state.
///
/// The raw JSON to write.
public override void WriteRawValue(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
///
/// Writes the beginning of a JSON array.
///
public override void WriteStartArray()
{
base.WriteStartArray();
AddParent(new BsonArray());
}
///
/// Writes the beginning of a JSON object.
///
public override void WriteStartObject()
{
base.WriteStartObject();
AddParent(new BsonObject());
}
///
/// Writes the property name of a name/value pair on a JSON object.
///
/// The name of the property.
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
_propertyName = name;
}
///
/// Closes this writer.
/// If is set to true, the underlying is also closed.
/// If is set to true, the JSON is auto-completed.
///
public override void Close()
{
base.Close();
if (CloseOutput)
{
_writer?.Close();
}
}
private void AddParent(BsonToken container)
{
AddToken(container);
_parent = container;
}
private void RemoveParent()
{
_parent = _parent.Parent;
}
private void AddValue(object value, BsonType type)
{
AddToken(new BsonValue(value, type));
}
internal void AddToken(BsonToken token)
{
if (_parent != null)
{
if (_parent is BsonObject bo)
{
bo.Add(_propertyName, token);
_propertyName = null;
}
else
{
((BsonArray)_parent).Add(token);
}
}
else
{
if (token.Type != BsonType.Object && token.Type != BsonType.Array)
{
throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null);
}
_parent = token;
_root = token;
}
}
#region WriteValue methods
///
/// Writes a value.
/// An error will raised if the value cannot be written as a single JSON token.
///
/// The value to write.
public override void WriteValue(object value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger i)
{
SetWriteState(JsonToken.Integer, null);
AddToken(new BsonBinary(i.ToByteArray(), BsonBinaryType.Binary));
}
else
#endif
{
base.WriteValue(value);
}
}
///
/// Writes a null value.
///
public override void WriteNull()
{
base.WriteNull();
AddToken(BsonEmpty.Null);
}
///
/// Writes an undefined value.
///
public override void WriteUndefined()
{
base.WriteUndefined();
AddToken(BsonEmpty.Undefined);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(string value)
{
base.WriteValue(value);
AddToken(value == null ? BsonEmpty.Null : new BsonString(value, true));
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(int value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
[CLSCompliant(false)]
public override void WriteValue(uint value)
{
if (value > int.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(long value)
{
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
///
/// Writes a value.
///
/// The value to write.
[CLSCompliant(false)]
public override void WriteValue(ulong value)
{
if (value > long.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(float value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(double value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(bool value)
{
base.WriteValue(value);
AddToken(value ? BsonBoolean.True : BsonBoolean.False);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(short value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
[CLSCompliant(false)]
public override void WriteValue(ushort value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(char value)
{
base.WriteValue(value);
string s = null;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
s = value.ToString(CultureInfo.InvariantCulture);
#else
s = value.ToString();
#endif
AddToken(new BsonString(s, true));
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(byte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
[CLSCompliant(false)]
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(decimal value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
AddValue(value, BsonType.Date);
}
#if HAVE_DATE_TIME_OFFSET
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
AddValue(value, BsonType.Date);
}
#endif
///
/// Writes a [] value.
///
/// The [] value to write.
public override void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonBinary(value, BsonBinaryType.Binary));
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(Guid value)
{
base.WriteValue(value);
AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid));
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
///
/// Writes a value.
///
/// The value to write.
public override void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
#endregion
///
/// Writes a [] value that represents a BSON object id.
///
/// The Object ID value to write.
public void WriteObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value.Length != 12)
{
throw JsonWriterException.Create(this, "An object id must be 12 bytes", null);
}
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddValue(value, BsonType.Oid);
}
///
/// Writes a BSON regex.
///
/// The regex pattern.
/// The regex options.
public void WriteRegex(string pattern, string options)
{
ValidationUtils.ArgumentNotNull(pattern, nameof(pattern));
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddToken(new BsonRegex(pattern, options));
}
}
}
================================================
FILE: Src/Newtonsoft.Json/CompatibilitySuppressions.xml
================================================
CP0001T:Newtonsoft.Json.Serialization.Actionlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Action`2lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Action`3lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Action`4lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Func`1lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Func`2lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Func`3lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Func`4lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.Serialization.Func`5lib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.SerializationBinderlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0001T:Newtonsoft.Json.TraceLevellib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0001T:System.Runtime.Serialization.Formatters.FormatterAssemblyStylelib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.JsonConvert.get_DefaultSettingslib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.JsonSerializerSettings.get_ReferenceResolverProviderlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.JsonContract.get_DefaultCreatorlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.JsonDictionaryContract.get_DictionaryKeyResolverlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.JsonObjectContract.get_ExtensionDataNameResolverlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.JsonProperty.get_SetIsSpecifiedlib/net20/Newtonsoft.Json.dlllib/net35/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.JsonSerializer.get_Binderlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.JsonSerializerSettings.get_Binderlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.ITraceWriter.get_LevelFilterlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.ITraceWriter.Trace(Newtonsoft.Json.TraceLevel,System.String,System.Exception)lib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.MemoryTraceWriter.get_LevelFilterlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0002M:Newtonsoft.Json.Serialization.MemoryTraceWriter.Trace(Newtonsoft.Json.TraceLevel,System.String,System.Exception)lib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0006M:Newtonsoft.Json.Serialization.ITraceWriter.Trace(System.Diagnostics.TraceLevel,System.String,System.Exception)lib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0006P:Newtonsoft.Json.Serialization.ITraceWriter.LevelFilterlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dllCP0007T:Newtonsoft.Json.Serialization.DefaultSerializationBinderlib/netstandard1.3/Newtonsoft.Json.dlllib/netstandard2.0/Newtonsoft.Json.dll
================================================
FILE: Src/Newtonsoft.Json/ConstructorHandling.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
///
/// Specifies how constructors are used when initializing objects during deserialization by the .
///
public enum ConstructorHandling
{
///
/// First attempt to use the public default constructor, then fall back to a single parameterized constructor, then to the non-public default constructor.
///
Default = 0,
///
/// Json.NET will use a non-public default constructor before falling back to a parameterized constructor.
///
AllowNonPublicDefaultConstructor = 1
}
}
================================================
FILE: Src/Newtonsoft.Json/Converters/BinaryConverter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_LINQ || HAVE_ADO_NET
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if HAVE_ADO_NET
using System.Data.SqlTypes;
#endif
namespace Newtonsoft.Json.Converters
{
///
/// Converts a binary value to and from a base 64 string value.
///
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class BinaryConverter : JsonConverter
{
#if HAVE_LINQ
private const string BinaryTypeName = "System.Data.Linq.Binary";
private const string BinaryToArrayName = "ToArray";
private static ReflectionObject? _reflectionObject;
#endif
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
byte[] data = GetByteArray(value);
writer.WriteValue(data);
}
private byte[] GetByteArray(object value)
{
#if HAVE_LINQ
if (value.GetType().FullName == BinaryTypeName)
{
EnsureReflectionObject(value.GetType());
MiscellaneousUtils.Assert(_reflectionObject != null);
return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;
}
#endif
#if HAVE_ADO_NET
if (value is SqlBinary binary)
{
return binary.Value;
}
#endif
throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#if HAVE_LINQ
private static void EnsureReflectionObject(Type t)
{
if (_reflectionObject == null)
{
_reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
}
}
#endif
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing value of object being read.
/// The calling serializer.
/// The object value.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
byte[] data;
if (reader.TokenType == JsonToken.StartArray)
{
data = ReadByteArray(reader);
}
else if (reader.TokenType == JsonToken.String)
{
// current token is already at base64 string
// unable to call ReadAsBytes so do it the old fashion way
string encodedData = reader.Value!.ToString()!;
data = Convert.FromBase64String(encodedData);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)!
: objectType;
#if HAVE_LINQ
if (t.FullName == BinaryTypeName)
{
EnsureReflectionObject(t);
MiscellaneousUtils.Assert(_reflectionObject != null);
return _reflectionObject.Creator!(data);
}
#endif
#if HAVE_ADO_NET
if (t == typeof(SqlBinary))
{
return new SqlBinary(data);
}
#endif
throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
}
private byte[] ReadByteArray(JsonReader reader)
{
List byteList = new List();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Integer:
byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
return byteList.ToArray();
case JsonToken.Comment:
// skip
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
}
///
/// Determines whether this instance can convert the specified object type.
///
/// Type of the object.
///
/// true if this instance can convert the specified object type; otherwise, false.
///
public override bool CanConvert(Type objectType)
{
#if HAVE_LINQ
if (objectType.FullName == BinaryTypeName)
{
return true;
}
#endif
#if HAVE_ADO_NET
if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
{
return true;
}
#endif
return false;
}
}
}
#endif
================================================
FILE: Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Bson;
using System.Globalization;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Converters
{
///
/// Converts a to and from JSON and BSON.
///
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonObjectIdConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
BsonObjectId objectId = (BsonObjectId)value;
if (writer is BsonWriter bsonWriter)
{
bsonWriter.WriteObjectId(objectId.Value);
}
else
{
writer.WriteValue(objectId.Value);
}
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing value of object being read.
/// The calling serializer.
/// The object value.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Bytes)
{
throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
byte[] value = (byte[])reader.Value;
return new BsonObjectId(value);
}
///
/// Determines whether this instance can convert the specified object type.
///
/// Type of the object.
///
/// true if this instance can convert the specified object type; otherwise, false.
///
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(BsonObjectId));
}
}
}
================================================
FILE: Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
///
/// Creates a custom object.
///
/// The object type to convert.
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public abstract class CustomCreationConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing value of object being read.
/// The calling serializer.
/// The object value.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
T value = Create(objectType);
if (value == null)
{
throw new JsonSerializationException("No object created.");
}
serializer.Populate(reader, value);
return value;
}
///
/// Creates an object which will then be populated by the serializer.
///
/// Type of the object.
/// The created object.
public abstract T Create(Type objectType);
///
/// Determines whether this instance can convert the specified object type.
///
/// Type of the object.
///
/// true if this instance can convert the specified object type; otherwise, false.
///
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
///
/// Gets a value indicating whether this can write JSON.
///
///
/// true if this can write JSON; otherwise, false.
///
public override bool CanWrite => false;
}
}
================================================
FILE: Src/Newtonsoft.Json/Converters/DataSetConverter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ADO_NET
using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
///
/// Converts a to and from JSON.
///
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DataSetConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DataSet dataSet = (DataSet)value;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
DataTableConverter converter = new DataTableConverter();
writer.WriteStartObject();
foreach (DataTable table in dataSet.Tables)
{
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName);
converter.WriteJson(writer, table, serializer);
}
writer.WriteEndObject();
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing value of object being read.
/// The calling serializer.
/// The object value.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
// handle typed datasets
DataSet ds = (objectType == typeof(DataSet))
? new DataSet()
: (DataSet)Activator.CreateInstance(objectType)!;
DataTableConverter converter = new DataTableConverter();
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
DataTable? dt = ds.Tables[(string)reader.Value!];
bool exists = (dt != null);
dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!;
if (!exists)
{
ds.Tables.Add(dt);
}
reader.ReadAndAssert();
}
return ds;
}
///
/// Determines whether this instance can convert the specified value type.
///
/// Type of the value.
///
/// true if this instance can convert the specified value type; otherwise, false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}
}
}
#endif
================================================
FILE: Src/Newtonsoft.Json/Converters/DataTableConverter.cs
================================================
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ADO_NET
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System;
using System.Data;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
///
/// Converts a to and from JSON.
///
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
[RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
public class DataTableConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DataTable table = (DataTable)value;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartArray();
foreach (DataRow row in table.Rows)
{
writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
{
object columnValue = row[column];
if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value))
{
continue;
}
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
serializer.Serialize(writer, columnValue);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing value of object being read.
/// The calling serializer.
/// The object value.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (!(existingValue is DataTable dt))
{
// handle typed datasets
dt = (objectType == typeof(DataTable))
? new DataTable()
: (DataTable)Activator.CreateInstance(objectType)!;
}
// DataTable is inside a DataSet
// populate the name from the property name
if (reader.TokenType == JsonToken.PropertyName)
{
dt.TableName = (string)reader.Value!;
reader.ReadAndAssert();
if (reader.TokenType == JsonToken.Null)
{
return dt;
}
}
if (reader.TokenType != JsonToken.StartArray)
{
throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
reader.ReadAndAssert();
while (reader.TokenType != JsonToken.EndArray)
{
CreateRow(reader, dt, serializer);
reader.ReadAndAssert();
}
return dt;
}
private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer)
{
DataRow dr = dt.NewRow();
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
string columnName = (string)reader.Value!;
reader.ReadAndAssert();
DataColumn? column = dt.Columns[columnName];
if (column == null)
{
Type columnType = GetColumnDataType(reader);
column = new DataColumn(columnName, columnType);
dt.Columns.Add(column);
}
if (column.DataType == typeof(DataTable))
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.ReadAndAssert();
}
DataTable nestedDt = new DataTable();
while (reader.TokenType != JsonToken.EndArray)
{
CreateRow(reader, nestedDt, serializer);
reader.ReadAndAssert();
}
dr[columnName] = nestedDt;
}
else if (column.DataType.IsArray && column.DataType != typeof(byte[]))
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.ReadAndAssert();
}
List