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

Created Release: Json.NET 5.0 Release 5 (May 08, 2013)

$
0
0
  • New feature - Added global default serialization settings with JsonConvert.DefaultSettings
  • New feature - Added extension data support with JsonExtensionDataAttribute
  • New feature - Added NullValueHandling and DefaultValueHandling support to serializing dynamic types
  • Change - Changed some explicit interface methods on JArray to public to support use with ImpromtuInterface
  • Fix - Fixed deserializing non-ISO formatted date dictionary keys
  • Fix - Fixed values not being set when deserializing with DefaultValueHandling.IgnoreAndPopulate
  • Fix - Fixed deserializing with type named handling and assemblies loaded with Assembly.LoadFrom
  • Fix - Fixed deserializing Regexes when using StringEnumConverter
  • Fix - Fixed serializing and deserializing typed DataSets

New Post: Compact Framework MissingMethodException

$
0
0
I'm having a similar problem to this (same exception, same error message). Can you please post your solution?

I realize that this thread is really old, but this is the only instance that Google could find of someone having a similar problem.

Commented Issue: When JToken Equals Null Not Working As Expected [19663]

$
0
0
Given the following circumstance.
 
var value = new JValue(null, JTokenType.Null);
var failed = value == null; // should pass
 
This is important use case when using JObject, JValue, or JToken with the dynamic runtime. So that stuff like this can be supported:
 
var json = { "Name": "Nick Berardi", Age: null };
dynamic obj = /* json deserialized to JObject */
 
if (obj.Age == null)
Console.WriteLine("No Age Found");
 
I do realize that I can cast down to something like JToken and check for JTokenType.Null, but that really defeats the intent of the dynamic type in my opinion.
 
I believe the error is in this statement.
 
public bool Equals(JValue other)
{
if (other == null)
return false;
 
return ValuesEquals(this, other);
}
 
Should probably look something like this
 
public bool Equals(JValue other)
{
if (other == null && _valueType == JTokenType.Null)
return true;
 
if (other == null)
return false;
 
return ValuesEquals(this, other);
}
 
I believe this would satisfy the issue I am running in to.
Comments: ** Comment from web user: jimitndiaye **

I'm having the same problem. This used to work in v4.5.11 of the Nuget package but is broken in v5.0.5

New Post: For a big data, Jquery call back id randomly appears

$
0
0
I am confused. After the web service return JsonConvert.SerializeObject result,
there is an error in JSON.parse script. It seems for a larger query, the results always has "Jqueryxxxxxxxxxxxx". Examples below:

"Retries": 0,
"Employ);jQuery1710008925603404620341_1368119766228(ee": "test",

If I do a small query even for that bad record, it is okay. It seems that for a large record, the Jqueryxxxxx gets injected. Does any know have any idea? Thank you for any feedbacks.

Commented Issue: TypeNameHandling.Auto and Serializing Derived Type [23891]

$
0
0
Scenario:

```
public abstract class Entity { ... }
public class Cat : Entity { ... }
public class Dog : Entity { ... }
```

It would be nice if the following were to happen with TypeNameHandling.Auto:

```
JsonSerializer serializer = new JsonSerializer();

//I would expect $type for the Cat to be written in this case:
serializer.Serialize{Entity}(new Cat());

//But not in this case:
serializer.Serialize{Cat}(new Cat());
```
NOTE: Forgive the curly brackets, CodePlex Is eating my less than and greater than characters

The assumption being that if I have some abstraction in the layer that does my serialization, I'm probably going to have that same abstraction on the deserialization. Currently this doesn't work and I'm forced to switch to TypeNameHandling.All to get the $type of the top-level object written so it can be deserialized correctly on the other side.

Thoughts?
Comments: ** Comment from web user: itavantiq **

We are using the 5.0.5 version and we have exactly the same issue. The serialization of a derived type instance does not contain the $type node with the TypeNameHandling.Auto setting and therefore, client is not allowed to recognize with derived type is used.

The issue has been closed on March but we are still in trouve. Any thoughts?

Commented Issue: TypeNameHandling.Auto and Serializing Derived Type [23891]

$
0
0
Scenario:

```
public abstract class Entity { ... }
public class Cat : Entity { ... }
public class Dog : Entity { ... }
```

It would be nice if the following were to happen with TypeNameHandling.Auto:

```
JsonSerializer serializer = new JsonSerializer();

//I would expect $type for the Cat to be written in this case:
serializer.Serialize{Entity}(new Cat());

//But not in this case:
serializer.Serialize{Cat}(new Cat());
```
NOTE: Forgive the curly brackets, CodePlex Is eating my less than and greater than characters

The assumption being that if I have some abstraction in the layer that does my serialization, I'm probably going to have that same abstraction on the deserialization. Currently this doesn't work and I'm forced to switch to TypeNameHandling.All to get the $type of the top-level object written so it can be deserialized correctly on the other side.

Thoughts?
Comments: ** Comment from web user: JamesNK **

Use the SerializeObject overload that lets you specify a root object.

Created Issue: NullValueHandling not working [24273]

$
0
0
Hi James,

I am trying to skip the null values, but after upgrade to 4.5, NullValueHandling.Ignore settings are not working, it was working fine earlier. I am using it inside WebAPI, I even tried to setup the new DefaultSettings in Json.NET 5.0.5 Version, but still it's not working,

I am attaching the screenshot, Let me know, Thanks.

Created Issue: InvalidCastException when deserializing custom IConvertible [24285]

$
0
0
Since upgrading JSon.NET from 4.5 to 5.0.5 my custom value type (a mathematical Ratio class) no longer deserializes successfully. Instead I get an InvalidCastException.

Commented Issue: NullValueHandling not working [24273]

$
0
0
Hi James,

I am trying to skip the null values, but after upgrade to 4.5, NullValueHandling.Ignore settings are not working, it was working fine earlier. I am using it inside WebAPI, I even tried to setup the new DefaultSettings in Json.NET 5.0.5 Version, but still it's not working,

I am attaching the screenshot, Let me know, Thanks.
Comments: ** Comment from web user: JamesNK **

DefaultSettings doesn't work with WebAPI yet. You'll have to attach a demo with the problem.

Commented Issue: InvalidCastException when deserializing custom IConvertible [24285]

$
0
0
Since upgrading JSon.NET from 4.5 to 5.0.5 my custom value type (a mathematical `Ratio<T>` class that implements `IConvertible`) no longer deserializes successfully. Instead I get an `InvalidCastException`.

The problem occurs because for example a `Ratio<int>` value is serialized as single number string if the ratio represents a whole number, whereas it is serialised as a fraction (for example 1/2) otherwise. When deserializing an integer source value into a `Ratio<int>` target value, the conversion procedure recognizes both the source value (`Int32` type) and the target value (`Ratio<int>` type) as `IConvertible` and calls `Convert.ChangeType(intValue, typeof(Ratio<int>), culture)`, causing an `InvalidCastException` because the `System.Int32` class doesn't know how to convert to `Ratio<int>` values.

For this reason `Convert.ChangeType` should not be relied on when deserialising values into `IConvertible` types that are non-system types.
Comments: ** Comment from web user: JamesNK **

Which version were you using? Can you attach a demo of what used to work?

Created Issue: TypeConverter on Interfaces [24301]

$
0
0
In the current implementation of Json.NET, TypeConverters on interfaces and abstract classes are not handled properly (in my opinion). If such a converter exists on an interface, the following code fragment in the ConvertUtils.Convert(object initialValue, CultureInfo culture, Type targetType) method will throw an exception:

(lines 410ff)
if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");


But in the next lines, the correct handling of the existing type converter takes place. So I would suggest to remove the above lines from the code. This does not break any unit tests and works (at least in my scenario it worked perfectly).

The case where no type converter is placed on an interface/abstract class is handled at the very end of the method.

Commented Issue: InvalidCastException when deserializing custom IConvertible [24285]

$
0
0
Since upgrading JSon.NET from 4.5 to 5.0.5 my custom value type (a mathematical `Ratio<T>` class that implements `IConvertible`) no longer deserializes successfully. Instead I get an `InvalidCastException`.

The problem occurs because for example a `Ratio<int>` value is serialized as single number string if the ratio represents a whole number, whereas it is serialised as a fraction (for example 1/2) otherwise. When deserializing an integer source value into a `Ratio<int>` target value, the conversion procedure recognizes both the source value (`Int32` type) and the target value (`Ratio<int>` type) as `IConvertible` and calls `Convert.ChangeType(intValue, typeof(Ratio<int>), culture)`, causing an `InvalidCastException` because the `System.Int32` class doesn't know how to convert to `Ratio<int>` values.

For this reason `Convert.ChangeType` should not be relied on when deserialising values into `IConvertible` types that are non-system types.
Comments: ** Comment from web user: ggeurts **

My unit tests pass when using version 4.5.11, but fail under 5.0.5. I will try to get some sample code to illustrate the issue.

Commented Issue: InvalidCastException when deserializing custom IConvertible [24285]

$
0
0
Since upgrading JSon.NET from 4.5 to 5.0.5 my custom value type (a mathematical `Ratio<T>` class that implements `IConvertible`) no longer deserializes successfully. Instead I get an `InvalidCastException`.

The problem occurs because for example a `Ratio<int>` value is serialized as single number string if the ratio represents a whole number, whereas it is serialised as a fraction (for example 1/2) otherwise. When deserializing an integer source value into a `Ratio<int>` target value, the conversion procedure recognizes both the source value (`Int32` type) and the target value (`Ratio<int>` type) as `IConvertible` and calls `Convert.ChangeType(intValue, typeof(Ratio<int>), culture)`, causing an `InvalidCastException` because the `System.Int32` class doesn't know how to convert to `Ratio<int>` values.

For this reason `Convert.ChangeType` should not be relied on when deserialising values into `IConvertible` types that are non-system types.
Comments: ** Comment from web user: ggeurts **

```
namespace JsonConvertible
{
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Newtonsoft.Json;

class Program
{
static void Main(string[] args)
{
var ratio = new Ratio(2, 1);
var json = JsonConvert.SerializeObject(ratio);

// Throws exception in Newtonsoft.Json 5.0.5
var ratio2 = JsonConvert.DeserializeObject<Ratio>(json);
}
}

public struct Ratio: IConvertible, IFormattable, ISerializable
{
private readonly int _numerator;
private readonly int _denominator;

public Ratio(int numerator, int denominator)
{
_numerator = numerator;
_denominator = denominator;
}

#region Properties

public int Numerator
{
get { return _numerator; }
}

public int Denominator
{
get { return _denominator; }
}

public bool IsNan
{
get { return _denominator == 0; }
}

#endregion

#region Serialization operations

public Ratio(SerializationInfo info, StreamingContext context)
{
_numerator = info.GetInt32("n");
_denominator = info.GetInt32("d");
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("n", _numerator);
info.AddValue("d", _denominator);
}

#endregion

#region IConvertible Members

public TypeCode GetTypeCode()
{
return TypeCode.Object;
}

public bool ToBoolean(IFormatProvider provider)
{
return this._numerator == 0;
}

public byte ToByte(IFormatProvider provider)
{
return (byte)(this._numerator / this._denominator);
}

public char ToChar(IFormatProvider provider)
{
return Convert.ToChar(this._numerator / this._denominator);
}

public DateTime ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(this._numerator / this._denominator);
}

public decimal ToDecimal(IFormatProvider provider)
{
return (decimal)this._numerator / this._denominator;
}

public double ToDouble(IFormatProvider provider)
{
return this._denominator == 0
? double.NaN
: (double)this._numerator / this._denominator;
}

public short ToInt16(IFormatProvider provider)
{
return (short)(this._numerator / this._denominator);
}

public int ToInt32(IFormatProvider provider)
{
return this._numerator / this._denominator;
}

public long ToInt64(IFormatProvider provider)
{
return this._numerator / this._denominator;
}

public sbyte ToSByte(IFormatProvider provider)
{
return (sbyte)(this._numerator / this._denominator);
}

public float ToSingle(IFormatProvider provider)
{
return this._denominator == 0
? float.NaN
: (float)this._numerator / this._denominator;
}

public string ToString(IFormatProvider provider)
{
return this._denominator == 1
? this._numerator.ToString(provider)
: this._numerator.ToString(provider) + "/" + this._denominator.ToString(provider);
}

public object ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(ToDouble(provider), conversionType, provider);
}

public ushort ToUInt16(IFormatProvider provider)
{
return (ushort)(this._numerator / this._denominator);
}

public uint ToUInt32(IFormatProvider provider)
{
return (uint)(this._numerator / this._denominator);
}

public ulong ToUInt64(IFormatProvider provider)
{
return (ulong)(this._numerator / this._denominator);
}

#endregion

#region String operations

public override string ToString()
{
return ToString(CultureInfo.InvariantCulture);
}

public string ToString(string format, IFormatProvider formatProvider)
{
return ToString(CultureInfo.InvariantCulture);
}

public static Ratio Parse(string input)
{
return Parse(input, CultureInfo.InvariantCulture);
}

public static Ratio Parse(string input, IFormatProvider formatProvider)
{
Ratio result;
if (!TryParse(input, formatProvider, out result))
{
throw new FormatException(
string.Format(
CultureInfo.InvariantCulture,
"Text '{0}' is invalid text representation of ratio",
input));
}
return result;
}

public static bool TryParse(string input, out Ratio result)
{
return TryParse(input, CultureInfo.InvariantCulture, out result);
}

public static bool TryParse(string input, IFormatProvider formatProvider, out Ratio result)
{
if (input != null)
{
var fractionIndex = input.IndexOf('/');

int numerator;
if (fractionIndex < 0)
{
if (int.TryParse(input, NumberStyles.Integer, formatProvider, out numerator))
{
result = new Ratio(numerator, 1);
return true;
}
}
else
{
int denominator;
if (int.TryParse(input.Substring(0, fractionIndex), NumberStyles.Integer, formatProvider, out numerator) &&
int.TryParse(input.Substring(fractionIndex + 1), NumberStyles.Integer, formatProvider, out denominator))
{
result = new Ratio(numerator, denominator);
return true;
}
}
}

result = default(Ratio);
return false;
}

#endregion
}

}

```

Closed Issue: InvalidCastException when deserializing custom IConvertible [24285]

$
0
0
Since upgrading JSon.NET from 4.5 to 5.0.5 my custom value type (a mathematical `Ratio<T>` class that implements `IConvertible`) no longer deserializes successfully. Instead I get an `InvalidCastException`.

The problem occurs because for example a `Ratio<int>` value is serialized as single number string if the ratio represents a whole number, whereas it is serialised as a fraction (for example 1/2) otherwise. When deserializing an integer source value into a `Ratio<int>` target value, the conversion procedure recognizes both the source value (`Int32` type) and the target value (`Ratio<int>` type) as `IConvertible` and calls `Convert.ChangeType(intValue, typeof(Ratio<int>), culture)`, causing an `InvalidCastException` because the `System.Int32` class doesn't know how to convert to `Ratio<int>` values.

For this reason `Convert.ChangeType` should not be relied on when deserialising values into `IConvertible` types that are non-system types.
Comments: Thanks. Fixed

Commented Issue: TypeConverter on Interfaces [24301]

$
0
0
In the current implementation of Json.NET, TypeConverters on interfaces and abstract classes are not handled properly (in my opinion). If such a converter exists on an interface, the following code fragment in the ConvertUtils.Convert(object initialValue, CultureInfo culture, Type targetType) method will throw an exception:

(lines 410ff)
if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");


But in the next lines, the correct handling of the existing type converter takes place. So I would suggest to remove the above lines from the code. This does not break any unit tests and works (at least in my scenario it worked perfectly).

The case where no type converter is placed on an interface/abstract class is handled at the very end of the method.
Comments: ** Comment from web user: JamesNK **

Could you attach an example of the scenario that you think should work?


New Post: possible FileVersion and AssemblyVersion mismatch

$
0
0
We are using Json.NET 5.0.5 from NuGet and I noticed that FileVersion is 5.0.5.16108 but the AssemblyVersion is 4.5.0.0, is this by design? I would have thought that AssemblyVersion matched the NuGet version number.

I don't think i have noticed this before in earlier versions.

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: simon_laing **

Hi James,

There appears to be an issue with deserialising decimals with numbers larger than Math.Abs(long.MinValue).
for example, decimal.MaxValue.

1. ConvertUtils.Int64TryParse() returns ParseResult.Overflow
2. JsonTextReader.ParseNumber() throws because the value is not an integer when trying to parse into a BigInteger.

If ConvertUtils.Int64TryParse() returned ParseResult.Invalid then an attempt would be made to parse the value into a decimal/Double and would succeed.

Decimal.MaxValue parsing works correctly in versions 4.5.4 and 4.5.6

Created Unassigned: Serialized Guid not converting in JToken [24314]

$
0
0
When serializing a Guid property using the BSONWriter, loading the result in a JObject does not allow me to get the property using the "Value<>" method. The JToken uses the Extensions.cs instead of the same method used by the BsonWriter.

adding this to the Convert method in Extensions.cs

```

else if (token is byte[] && typeof(U)== typeof(Guid))
return (U)(object)(new Guid((byte[])(token as JValue)));

```
solves the problem.

Created Unassigned: [Win2003 & Newtonsoft.Json.dll (.NET2.0version)]Build issue! [24316]

$
0
0
When build in VS there is a exception occurs which is as following:
Missing compiler required member 'System.Runtime.CompilerServices.ExtensionAttribute..ctor'

Could you please explain what's the reason of this issue? And please help me to resolve this issue~
If you can not resolve this issue please let me know ASAP, Thx a lot :)

Commented Issue: TypeConverter on Interfaces [24301]

$
0
0
In the current implementation of Json.NET, TypeConverters on interfaces and abstract classes are not handled properly (in my opinion). If such a converter exists on an interface, the following code fragment in the ConvertUtils.Convert(object initialValue, CultureInfo culture, Type targetType) method will throw an exception:

(lines 410ff)
if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");


But in the next lines, the correct handling of the existing type converter takes place. So I would suggest to remove the above lines from the code. This does not break any unit tests and works (at least in my scenario it worked perfectly).

The case where no type converter is placed on an interface/abstract class is handled at the very end of the method.
Comments: ** Comment from web user: macandy13 **

Attached is a file that contains a sample that should cover the three cases where TypeConverter should be used store/restore interfaces, especially in combination with dictionaries.

I also adapted the code of Json.Net (version 5.0r5) to make the sample run. That required two changes, the one described above and another one that actually utilizes an associated TypeConverter to stringify dictionary keys.

It would be great if the two modifications could be part of the Json.NET deliver, since they do not break the unit tests but make TypeConverter handling more consistent (at least from my point of view).

Viewing all 1767 articles
Browse latest View live


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