Quantcast
Channel: Json.NET
Viewing all 1767 articles
Browse latest View live

Updated Wiki: Home

$
0
0

Json.NET

Json.NET is a popular high-performance JSON framework for .NET

Features

  • 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, Silverlight, Windows Phone and Windows 8.

The JSON serializer 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.

Download Json.NET from CodePlex or install using NuGet

NuGet

Find getting started guides and comprehensive API documentation here.

Donate

Json.NET is a personal open source project. Started in 2006, I have put hundreds of hours adding, refining and tuning Json.NET with the goal to make it not just the best JSON serializer for .NET but the best serializer for any computer language. I need your help to achieve this.

Click here to lend your support to: Json.NET and make a donation at www.pledgie.com !

Feature Comparison

 Json.NETDataContractJsonSerializerJavaScriptSerializer
Supports JSON   
Supports BSON
   
Supports JSON Schema
   
Supports .NET 2.0
   
Supports .NET 3.5
   
Supports .NET 4.0   
Supports .NET 4.5   
Supports Silverlight   
Supports Windows Phone   
Supports Windows 8   
Supports Portable Class Library   
Open Source   
MIT License   
LINQ to JSON   
Thread Safe   
XPath-like JSON query syntax   
Indented JSON support
   
Efficient dictionary serialization   
Nonsensical dictionary serialization   
Deserializes IList, IEnumerable, ICollection, IDictionary properties
   
Serializes circular references
   
Supports serializing objects by reference
   
Deserializes polymorphic properties and collections
   
Serializes and deserializes multidimensional arrays
   
Supports including type names with JSON   
Globally customize serialization process   
Supports excluding null values when serializing
   
Supports SerializationBinder
   
Conditional property serialization
   
Includes line number information in errors
   
Converts XML to JSON and JSON to XML
   
JSON Schema validation
   
JSON Schema generation from .NET types
   
Camel case JSON property names
   
Non-default constructors support
   
Serialization error handling
   
Supports populating an existing object
   
Efficiently serializes byte arrays as base64 text
   
Handles NaN, Infinity, -Infinity and undefined
   
Handles JavaScript constructors   
Serializes .NET 4.0 dynamic objects
   
Serializes ISerializable objects
   
Supports serializing enums to their text name   
JSON recursion limit support
 
  
Attribute property name customization   
Attribute property order customization   
Attribute property required customization   
Supports ISO8601 dates   
Supports JavaScript constructor dates   
Supports Microsoft AJAX dates   
Unquoted property names support   
Raw JSON support   
Supports reading and writing comments   
Supports BigInteger   
Serializes anonymous types   
Deserializes anonymous types   
Deserializes read only collections   
Opt-in mode serialization   
Opt-out mode serialization   
Field (Serializable) mode serialization 
  
Efficiently stream reading and writing JSON   
Single or double quote JSON content   
Supports overriding a type's serialization   
Supports OnDeserialized, OnSerializing, OnSerialized and OnDeserializing attributes   
Supports serializing private properties   
DataMember attribute support   
MetdataType attribute support   
DefaultValue attribute support   
Serializes DataSets and DataTables   
Serailizes Entity Framework   
Serializes nHibernate   
Case-insensitive property deserialization   
Tracing   

Performance Comparison

The source code for this benchmark is included in the Json.NET unit tests.

My Blog

My blog can be found at http://james.newtonking.com where I post news and updates about Json.NET.

My Twitter

My twitter account can be found at @JamesNK


Updated Release: Json.NET 5.0 Release 2 (Apr 08, 2013)

$
0
0
  • Remove - Removed WP8 library
  • Fix - Fixed required System.Numerics.dll reference by removing BigInteger from external API calls

Released: Json.NET 5.0 Release 2 (Apr 08, 2013)

$
0
0
  • Remove - Removed WP8 library
  • Fix - Fixed required System.Numerics.dll reference by removing BigInteger from external API calls

Reviewed: Json.NET 5.0 Release 3 (Apr 14, 2013)

$
0
0
Rated 5 Stars (out of 5) - great work !

Created Issue: DefaultSerializationBinder.GetTypeNameFromTypeKey() : Check loaded assemblies before calling LoadWithPartialName() [24174]

$
0
0
Greetings and thanks for this fantastic library.

My issue is this:

When I attempt to deserialize an object that was serialized with types from assemblies that were loaded from outside of the GAC and EXE directories, it fails because it cannot find the assembly in either place when calling Assembly.LoadWithPartialName().

If, however, the list of loaded assemblies is checked with AppDomain.CurrentDomain.GetAssemblies() for a matching assemblyname, this assembly can be used without a call to LoadWithPartialName.

I was able to make this change to the source to solve this issue, but perhaps there is a more elegant solution that doesn't involve source modification, or this feature could be added without much impact?

Created Issue: Deserilizing inotegers in mono [24176]

$
0
0
trying to deserialize an object containing an integer property fails when running under mono.

```
public class TypeWithNumbers
{
int Id { get; set; }
}

[Test]
public void should_be_able_to_deserialize_numbers()
{
var quality = new TypeWithNumbers { Id = 12 };

var json = JsonConvert.SerializeObject(quality);

JsonConvert.DeserializeObject(json);
}
```

the above test passed in Windows and .NET but running the same test on the same windows machine but under mono fails with this exception

```
failed: System.MissingMethodException : Method not found: 'System.Numerics.BigInteger.Parse'.
at Newtonsoft.Json.JsonTextReader.ParseValue () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonTextReader.ReadInternal () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonTextReader.Read () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonWriter.WriteToken (Newtonsoft.Json.JsonReader reader, Int32 initialDepth, Boolean writeChildren) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJObject (Newtonsoft.Json.JsonReader reader) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in <filename unknown>:0

Missing method System.Numerics.BigInteger::Parse(string,IFormatProvider) in assembly C:\Program Files (x86)\Mono-2.10.9\lib\mono\gac\System.Numerics\4.0.0.0__b77a5c561934e089\System.Numerics.dll
```

New Post: Selecting the Correct constructor Without an Attribute?

Created Issue: Data loss when serializing a large decimal [24183]

$
0
0
Hi,

I am trying to serialize a list of objects, which contains decimals some times. When I serialize it using BSON it usually works. In some cases, in particular when serializing large decimal values, the BSON serializer loses data.

An example:

using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;

namespace NewtonsoftJsonBugReport
{
static class Program
{
class X
{
public X()
{ }

public X(decimal d)
{
this.Data = d;
}

public decimal Data { get; set; }
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
decimal d = 42386543286548654368345865241M;

byte[] output;

Console.WriteLine("Input value {0}", d);

JsonSerializer jsonSerializer = new JsonSerializer();

using (MemoryStream ms = new MemoryStream())
{
using (JsonWriter writer = new BsonWriter(ms))
{
jsonSerializer.Serialize(writer, new X(d));
}

output = ms.ToArray();
}

using (MemoryStream ms = new MemoryStream(output))
{
using (JsonReader reader = new BsonReader(ms))
{
X x = jsonSerializer.Deserialize<X>(reader);

d = x.Data;
}
}

Console.WriteLine("Output value {0}", d);

Console.ReadKey();
}
}
}

As you will see, the input is different from the output. This is obviously unwanted, but it also happens silently.

The cause can be found in the BsonBinaryWriter (about line 114)

case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;

All numerics, except Int32 and Int64, are converted to Double, which causes the loss of data.

My suggestion would be:
1. To check if the converted data is the same as the input data. Like this, assuming that we are writing a Decimal:

decimal originalValue = (decimal)value.Value;
double d = Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
decimal convertedValue = Convert.ToDecimal(d);

if (originalValue != convertedValue)
{
throw new Exception("Cannot convert value to a lossless representative.");
}

2. To include Decimal, Float and other types in BsonType so the writer can convert to and from the right type.

Looking forward to your reply.

Closed Issue: Data loss when serializing a large decimal [24183]

$
0
0
Hi,

I am trying to serialize a list of objects, which contains decimals some times. When I serialize it using BSON it usually works. In some cases, in particular when serializing large decimal values, the BSON serializer loses data.

An example:

``` c#
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;

namespace NewtonsoftJsonBugReport
{
static class Program
{
class X
{
public X()
{ }

public X(decimal d)
{
this.Data = d;
}

public decimal Data { get; set; }
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
decimal d = 42386543286548654368345865241M;

byte[] output;

Console.WriteLine("Input value {0}", d);

JsonSerializer jsonSerializer = new JsonSerializer();

using (MemoryStream ms = new MemoryStream())
{
using (JsonWriter writer = new BsonWriter(ms))
{
jsonSerializer.Serialize(writer, new X(d));
}

output = ms.ToArray();
}

using (MemoryStream ms = new MemoryStream(output))
{
using (JsonReader reader = new BsonReader(ms))
{
X x = jsonSerializer.Deserialize<X>(reader);

d = x.Data;
}
}

Console.WriteLine("Output value {0}", d);

Console.ReadKey();
}
}
}
```

As you will see, the input is different from the output. This is obviously unwanted, but it also happens silently.

The cause can be found in the BsonBinaryWriter (about line 114)

``` c#
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
```

All numerics, except Int32 and Int64, are converted to Double, which causes the loss of data.

My suggestion would be:
1. To check if the converted data is the same as the input data. Like this, assuming that we are writing a Decimal:

decimal originalValue = (decimal)value.Value;
double d = Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
decimal convertedValue = Convert.ToDecimal(d);

``` c#
if (originalValue != convertedValue)
{
throw new Exception("Cannot convert value to a lossless representative.");
}
```

2. To include Decimal, Float and other types in BsonType so the writer can convert to and from the right type.

Looking forward to your reply.
Comments: The BSON spec doesn't have a decimal data type - http://bsonspec.org/

A work around is to create a JsonConverter which writes decimals as strings.

Closed Issue: Deserializing integers in mono [24176]

$
0
0
trying to deserialize an object containing an integer property fails when running under mono.

```
public class TypeWithNumbers
{
int Id { get; set; }
}

[Test]
public void should_be_able_to_deserialize_numbers()
{
var quality = new TypeWithNumbers { Id = 12 };

var json = JsonConvert.SerializeObject(quality);

JsonConvert.DeserializeObject(json);
}
```

the above test passed in Windows and .NET but running the same test on the same windows machine but under mono fails with this exception

```
failed: System.MissingMethodException : Method not found: 'System.Numerics.BigInteger.Parse'.
at Newtonsoft.Json.JsonTextReader.ParseValue () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonTextReader.ReadInternal () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonTextReader.Read () [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonWriter.WriteToken (Newtonsoft.Json.JsonReader reader, Int32 initialDepth, Boolean writeChildren) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJObject (Newtonsoft.Json.JsonReader reader) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in <filename unknown>:0

Missing method System.Numerics.BigInteger::Parse(string,IFormatProvider) in assembly C:\Program Files (x86)\Mono-2.10.9\lib\mono\gac\System.Numerics\4.0.0.0__b77a5c561934e089\System.Numerics.dll
```
Comments: Log a bug with mono and use a 4.5 version of Json.NET until they fix it.

Commented Issue: DefaultSerializationBinder.GetTypeNameFromTypeKey() : Check loaded assemblies before calling LoadWithPartialName() [24174]

$
0
0
Greetings and thanks for this fantastic library.

My issue is this:

When I attempt to deserialize an object that was serialized with types from assemblies that were loaded from outside of the GAC and EXE directories, it fails because it cannot find the assembly in either place when calling Assembly.LoadWithPartialName().

If, however, the list of loaded assemblies is checked with AppDomain.CurrentDomain.GetAssemblies() for a matching assemblyname, this assembly can be used without a call to LoadWithPartialName.

I was able to make this change to the source to solve this issue, but perhaps there is a more elegant solution that doesn't involve source modification, or this feature could be added without much impact?
Comments: ** Comment from web user: JamesNK **

Could you attach your source code and an example of the problem it solves?

Commented Issue: Data loss when serializing a large decimal [24183]

$
0
0
Hi,

I am trying to serialize a list of objects, which contains decimals some times. When I serialize it using BSON it usually works. In some cases, in particular when serializing large decimal values, the BSON serializer loses data.

An example:

``` c#
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;

namespace NewtonsoftJsonBugReport
{
static class Program
{
class X
{
public X()
{ }

public X(decimal d)
{
this.Data = d;
}

public decimal Data { get; set; }
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
decimal d = 42386543286548654368345865241M;

byte[] output;

Console.WriteLine("Input value {0}", d);

JsonSerializer jsonSerializer = new JsonSerializer();

using (MemoryStream ms = new MemoryStream())
{
using (JsonWriter writer = new BsonWriter(ms))
{
jsonSerializer.Serialize(writer, new X(d));
}

output = ms.ToArray();
}

using (MemoryStream ms = new MemoryStream(output))
{
using (JsonReader reader = new BsonReader(ms))
{
X x = jsonSerializer.Deserialize<X>(reader);

d = x.Data;
}
}

Console.WriteLine("Output value {0}", d);

Console.ReadKey();
}
}
}
```

As you will see, the input is different from the output. This is obviously unwanted, but it also happens silently.

The cause can be found in the BsonBinaryWriter (about line 114)

``` c#
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
```

All numerics, except Int32 and Int64, are converted to Double, which causes the loss of data.

My suggestion would be:
1. To check if the converted data is the same as the input data. Like this, assuming that we are writing a Decimal:

decimal originalValue = (decimal)value.Value;
double d = Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
decimal convertedValue = Convert.ToDecimal(d);

``` c#
if (originalValue != convertedValue)
{
throw new Exception("Cannot convert value to a lossless representative.");
}
```

2. To include Decimal, Float and other types in BsonType so the writer can convert to and from the right type.

Looking forward to your reply.
Comments: ** Comment from web user: patrickhofman **

Hi James,

I understand the problem/cause. Would it still be possible to add the check to prevent data loss?

Patrick

Reopened Issue: Data loss when serializing a large decimal [24183]

$
0
0
Hi,

I am trying to serialize a list of objects, which contains decimals some times. When I serialize it using BSON it usually works. In some cases, in particular when serializing large decimal values, the BSON serializer loses data.

An example:

``` c#
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;

namespace NewtonsoftJsonBugReport
{
static class Program
{
class X
{
public X()
{ }

public X(decimal d)
{
this.Data = d;
}

public decimal Data { get; set; }
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
decimal d = 42386543286548654368345865241M;

byte[] output;

Console.WriteLine("Input value {0}", d);

JsonSerializer jsonSerializer = new JsonSerializer();

using (MemoryStream ms = new MemoryStream())
{
using (JsonWriter writer = new BsonWriter(ms))
{
jsonSerializer.Serialize(writer, new X(d));
}

output = ms.ToArray();
}

using (MemoryStream ms = new MemoryStream(output))
{
using (JsonReader reader = new BsonReader(ms))
{
X x = jsonSerializer.Deserialize<X>(reader);

d = x.Data;
}
}

Console.WriteLine("Output value {0}", d);

Console.ReadKey();
}
}
}
```

As you will see, the input is different from the output. This is obviously unwanted, but it also happens silently.

The cause can be found in the BsonBinaryWriter (about line 114)

``` c#
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
```

All numerics, except Int32 and Int64, are converted to Double, which causes the loss of data.

My suggestion would be:
1. To check if the converted data is the same as the input data. Like this, assuming that we are writing a Decimal:

decimal originalValue = (decimal)value.Value;
double d = Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
decimal convertedValue = Convert.ToDecimal(d);

``` c#
if (originalValue != convertedValue)
{
throw new Exception("Cannot convert value to a lossless representative.");
}
```

2. To include Decimal, Float and other types in BsonType so the writer can convert to and from the right type.

Looking forward to your reply.

New Post: 4.5.11 to 5.0.3 Breaking Changes?

$
0
0
Is there a list somewhere of breaking changes between 4.5.11 and 5.0.3?

I am getting a compile error because the JsonSchema type no longer has Identity or Options properties.

New Post: Parsing Nested Object as List

$
0
0
i have a json formed as this
{ "caption" : "",
  "description" : "",
  "id" : 5706,
  "images" : { "full" : { "height" : 338,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4.jpg",
          "width" : 619
        },
      "large" : { "height" : 338,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4.jpg",
          "width" : 619
        },
      "large-thumb" : { "height" : 140,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4-222x140.jpg",
          "width" : 222
        },
      "medium" : { "height" : 163,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4-300x163.jpg",
          "width" : 300
        },
      "slider-image" : { "height" : 300,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4-619x300.jpg",
          "width" : 619
        },
      "small-thumb" : { "height" : 60,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4-80x60.jpg",
          "width" : 80
        },
      "thumbnail" : { "height" : 150,
          "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4-150x150.jpg",
          "width" : 150
        }
    },
  "mime_type" : "image/jpeg",
  "parent" : 5705,
  "slug" : "htc-desire-l-lead4",
  "title" : "htc-desire-l-lead4",
  "url" : "http://tecnonation.net/wp-content/uploads/2013/04/htc-desire-l-lead4.jpg"
}
and i need to Serialize the Images Array in the Image class Declared this way
public class Image
    {
        [JsonProperty("???")]
        public string Type { get; set; }

        [JsonProperty("url")]
        public string Url { get; set; }

        [JsonProperty("width")]
        public int Width { get; set; }

        [JsonProperty("height")]
        public int Height { get; set; }
    }
with type as the Name of the object
how can i solve this?

Reviewed: Json.NET 5.0 Release 3 (avr. 19, 2013)

$
0
0
Rated 5 Stars (out of 5) - Amazing work. The most flexible json serializer I have found finished to convince me with a great performance improvement. thank you.

Created Issue: Inconsistent handling of XmlQualifiedName [24190]

$
0
0
Using the latest prerelease version 5.0.3, If I serialize an XmlQualified name like this:

```
var json = JsonConvert.SerializeObject(new XmlQualifiedName("Foo", "urn:foo"));
```

Produces the following JSON:

```
{"Namespace":"urn:foo","Name":"Foo","IsEmpty":false}
```

But taking that exact string and feeding it back through JSON.NET like so:

```
var qname = JsonConvert.DeserializeObject<XmlQualifiedName>(json);
```

Produces an empty object:

```
{}
```

Commented Issue: Inconsistent handling of XmlQualifiedName [24190]

$
0
0
Using the latest prerelease version 5.0.3, If I serialize an XmlQualified name like this:

```
var json = JsonConvert.SerializeObject(new XmlQualifiedName("Foo", "urn:foo"));
```

Produces the following JSON:

```
{"Namespace":"urn:foo","Name":"Foo","IsEmpty":false}
```

But taking that exact string and feeding it back through JSON.NET like so:

```
var qname = JsonConvert.DeserializeObject<XmlQualifiedName>(json);
```

Produces an empty object:

```
{}
```
Comments: ** Comment from web user: taschmidt **

Ok, now that I think about this further, I guess this makes sense. Those properties aren't deserialized because there are no setters for them.

Commented Issue: DefaultSerializationBinder.GetTypeNameFromTypeKey() : Check loaded assemblies before calling LoadWithPartialName() [24174]

$
0
0
Greetings and thanks for this fantastic library.

My issue is this:

When I attempt to deserialize an object that was serialized with types from assemblies that were loaded from outside of the GAC and EXE directories, it fails because it cannot find the assembly in either place when calling Assembly.LoadWithPartialName().

If, however, the list of loaded assemblies is checked with AppDomain.CurrentDomain.GetAssemblies() for a matching assemblyname, this assembly can be used without a call to LoadWithPartialName.

I was able to make this change to the source to solve this issue, but perhaps there is a more elegant solution that doesn't involve source modification, or this feature could be added without much impact?
Comments: ** Comment from web user: Millsington **

Turns out 4.5.10.15407 does not have this problem so that is probably a better place to look into what changed to cause this issue.

Here's a Visual Studio solution that demonstrates the problem. Just change the path at the top of the startup form to point to the DLL output of the ClassLibrary2 project.

Commented Issue: DefaultSerializationBinder.GetTypeNameFromTypeKey() : Check loaded assemblies before calling LoadWithPartialName() [24174]

$
0
0
Greetings and thanks for this fantastic library.

My issue is this:

When I attempt to deserialize an object that was serialized with types from assemblies that were loaded from outside of the GAC and EXE directories, it fails because it cannot find the assembly in either place when calling Assembly.LoadWithPartialName().

If, however, the list of loaded assemblies is checked with AppDomain.CurrentDomain.GetAssemblies() for a matching assemblyname, this assembly can be used without a call to LoadWithPartialName.

I was able to make this change to the source to solve this issue, but perhaps there is a more elegant solution that doesn't involve source modification, or this feature could be added without much impact?
Comments: ** Comment from web user: Millsington **

Very sorry, for some reason the assembly version was being misreported in the add reference dialog, 4.5 does still have this issue.

My solution was this (in DefaultSerializationBinder.cs):

```
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
string assemblyName = typeNameKey.AssemblyName;
string typeName = typeNameKey.TypeName;

if (assemblyName != null)
{
Assembly assembly = null;

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assy in loadedAssemblies)
{
if (assy.FullName == assemblyName)
assembly = assy;
}

#if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE)
// look, I don't like using obsolete methods as much as you do but this is the only way
// Assembly.Load won't check the GAC for a partial name
#pragma warning disable 618,612
if (assembly == null)
assembly = Assembly.LoadWithPartialName(assemblyName);
#pragma warning restore 618,612
```

Pure hack, I know.

Viewing all 1767 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>