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

Commented Unassigned: SelectToken("$type") throws JsonException [25193]

$
0
0
The following code works with 5.0.8, but throws a JsonException with 6.0.1 when calling SelectToken("$type")

var json = "{$type : \"test\", property1 : \"value1\"}";
var obj = JsonConvert.DeserializeObject<JObject>(json);

// this line works
var property1 = obj.SelectToken("property1");

// this line throws with the 6.0.1 package - "Unexpected character while parsing path: t"
var docType = obj.SelectToken("$type");
Comments: ** Comment from web user: nergmerdle **

This is marked fixed, but still seems to be broken. See: [https://dotnetfiddle.net/sbeW40](https://dotnetfiddle.net/sbeW40)


Commented Unassigned: SelectToken("$type") throws JsonException [25193]

$
0
0
The following code works with 5.0.8, but throws a JsonException with 6.0.1 when calling SelectToken("$type")

var json = "{$type : \"test\", property1 : \"value1\"}";
var obj = JsonConvert.DeserializeObject<JObject>(json);

// this line works
var property1 = obj.SelectToken("property1");

// this line throws with the 6.0.1 package - "Unexpected character while parsing path: t"
var docType = obj.SelectToken("$type");
Comments: ** Comment from web user: nergmerdle **

Ugh, never mind. It appears that dotnetfiddle is not using the latest version of Json.Net as I instructed it to. After downloading the Json.Net packages from NuGet and testing locally, I see this bug was indeed fixed in 6.0.3.

Commented Unassigned: Use System.IO.Stream async IO functions to offer async serialization and deserialization [25576]

$
0
0
Hello -

In .NET 4.5, async I/O methods were added to [System.IO.Stream](http://msdn.microsoft.com/en-us/library/System.IO.Stream_methods(v=vs.110).aspx). It would be awesome if JsonTextReader and JsonSerializer added support for these methods to allow for DeserializeAsync and SerializeAsync. This would allow users to increase throughput through the serializer - they would not have to load the entire resource into an in-memory string first to avoid blocking on stream.Read calls. And users who are currently using streaming Deserialization and Serialization would get the benefit of reducing their dependence on expensive OS threads when avoiding blocking by switching to the async methods.

Thanks!

Andrew Gaspar
Comments: ** Comment from web user: JamesNK **

This won't happen anytime soon, if ever. Making json.net async will be a huge amount of work. Pretty much every method will need an async and non-async version.

New Post: In DeserializeXNode, Utc datetime Convert in Local Time

$
0
0
I received json from another service provider, Service provider given "createDate" as a json attribute which contain "UTC" date-time format of that country where file was created, when i de-serialize json data using "JsonConvert.DeserializeXNode" i get wrong data-time. I am giving some example of these problem.

Code :
string jsonData = @"{ '@Id': 1, 'Email': 'james@example.com', 'Active': true, 'CreatedDate': '2013-01-20T23:50:00+05:30', 'Roles': ['User', 'Admin' ], 'Team': {'@Id': 2, 'Name': 'Software Developers', 'Description': 'Creators of fine software products and services.' }}";

XNode objXNode = JsonConvert.DeserializeXNode(jsonData, "Root");
Console.WriteLine(objXNode.ToString());
Console.Read();

OutPut is:

<Root Id="1"> james@example.com<Active>true</Active> <CreatedDate>2013-01-20T18:20:00+00:00</CreatedDate> <Roles>User</Roles> <Roles>Admin</Roles> <Team Id="2"> <Name>Software Developers</Name> <Description>Creators of fine software products and services.</Description> </Team>
</Root>


Please Resolve this problem.

Created Unassigned: JsonConvert.DeserializeXNode not available for WP8.1 anymore? [25828]

$
0
0
I updated Json.Net from 6.0.3 to 6.0.6 today and found that JsonConvert.DeserializeXNode is not available for WP8.1 anymore, but is still working in my WinRT background task and Windows app.

Do I have to change my code or what happened? ;)

Thanks in advance.

Created Unassigned: Deserialization of invalid date error does not include position information when using IsoDateTimeConverter [25829]

$
0
0
If a date is read with an invalid format, the error message does not include any information about the position of the error.

Using this model:
class TestModel
{
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.IsoDateTimeConverter))]
public DateTime Date { get; set; }
}

When deserializing the JSON:

{ date: "testc" }

Yields the exception with the error message:

The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.

But should yield the message:

Could not convert string to DateTime: testc. Path 'date', line 1, position 15.

Created Unassigned: JArray.Parse and JsonConvert.DeserializeObject accept invalid JSON arrays [25835]

$
0
0
`JArray.Parse` and `JsonConvert.DeserializeObject` will both accept the following invalid JSON strings and parse them to `JArray`s (note the trailing commas and no closing bracket):

"[1,"
"[1,2,"

Additionally, `JsonConvert.DeserializeObject` will also accept the following invalid JSON strings and parse them to `JArray`s, but `JArray.Parse` will return null:

"[1"
"[1,2"

Reviewed: Json.NET 6.0 Release 6 (十一月 24, 2014)

$
0
0
Rated 3 Stars (out of 5) - just try it

Created Unassigned: JArray.Values doesn't work with values larger than an Int32 [25836]

$
0
0
foreach(UInt64 value in JArray.Parse("[ 18446744073709551615]").Values<UInt64>())
{
Console.WriteLine(value);
}

Object must implement IConvertible.

mscorlib.dll!System.Convert.ChangeType(object value, System.Type conversionType, System.IFormatProvider provider) + 0x6cd bytes
Newtonsoft.Json.dll!Newtonsoft.Json.Linq.Extensions.Convert<Newtonsoft.Json.Linq.JToken,ulong>(Newtonsoft.Json.Linq.JToken token) Line 278 + 0x51 bytes C#
Newtonsoft.Json.dll!Newtonsoft.Json.Linq.Extensions.Convert<Newtonsoft.Json.Linq.JToken,ulong>(System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken> source) Line 243 + 0x22 bytes C#

Created Unassigned: sbyte? operator doesn't work for negative values [25837]

$
0
0
```
/// <summary>
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{SByte}"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
[CLSCompliant(false)]
public static explicit operator sbyte?(JToken value)
{
if (value == null)
return null;

JValue v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (v.Value is BigInteger)
return (sbyte?)(BigInteger)v.Value;
#endif

return (v.Value != null) ? (sbyte?)Convert.ToByte(v.Value, CultureInfo.InvariantCulture) : null;
}

```
Convert.ToByte seems to be wrong and should be ToSByte
__return (v.Value != null) ? (sbyte?)Convert.ToSByte(v.Value, CultureInfo.InvariantCulture) : null;__

Reviewed: Json.NET 6.0 Release 6 (十一月 26, 2014)

$
0
0
Rated 5 Stars (out of 5) - 速度快,使用够方便!

Reviewed: Json.NET 6.0 Release 6 (十一月 27, 2014)

$
0
0
Rated 5 Stars (out of 5) - Super Easy to Use!!!

New Post: Serializing - Deserializing Dictionary

$
0
0
So I have a Dictionary<string, string>, I serialize it on one end, the go to deserialize on the other, but it always fails with:

Unable to cast object of type 'System.String' to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'.

This is an example of the return that I've pared down for simplicity to test, but it still won't deserialize this.

"\"{\\"includeLabel\\":\\"True,False\\"}\""

If I break and manually change this to, "{'includeLabel':'True,False'}" before it tries to deserialize it, it works.

So I added,
string resp = GetResponse("WebAPI URL Here");

            __resp = resp.Replace("\\", "");
            resp = resp.Substring(1, resp.Length - 1);
            resp = resp.Substring(0, resp.Length - 1);__

            Dictionary<string, string> barcodeParams = JsonConvert.DeserializeObject<Dictionary<string, string>>(resp);
Which gets deserialized correctly. Is this something that can be accounted for in settings without having to throw that specific code at it?

Closed Unassigned: sbyte? operator doesn't work for negative values [25837]

$
0
0
```
/// <summary>
/// Performs an explicit conversion from <see cref="Newtonsoft.Json.Linq.JToken"/> to <see cref="Nullable{SByte}"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
[CLSCompliant(false)]
public static explicit operator sbyte?(JToken value)
{
if (value == null)
return null;

JValue v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (v.Value is BigInteger)
return (sbyte?)(BigInteger)v.Value;
#endif

return (v.Value != null) ? (sbyte?)Convert.ToByte(v.Value, CultureInfo.InvariantCulture) : null;
}

```
Convert.ToByte seems to be wrong and should be ToSByte
__return (v.Value != null) ? (sbyte?)Convert.ToSByte(v.Value, CultureInfo.InvariantCulture) : null;__
Comments: Fixed

Closed Unassigned: JArray.Parse and JsonConvert.DeserializeObject accept invalid JSON arrays [25835]

$
0
0
`JArray.Parse` and `JsonConvert.DeserializeObject` will both accept the following invalid JSON strings and parse them to `JArray`s (note the trailing commas and no closing bracket):

"[1,"
"[1,2,"

Additionally, `JsonConvert.DeserializeObject` will also accept the following invalid JSON strings and parse them to `JArray`s, but `JArray.Parse` will return null:

"[1"
"[1,2"
Comments: They throw exceptions in the latest version.

Created Unassigned: A way to simplify serialization usage from MongoDB serialization mechanism [25841]

$
0
0
1.Add a static member and property to JsonConvert class:
```
public static class JsonConvert
{
private static readonly JsonConverterCollection _registeredJsonConverters = new JsonConverterCollection();
/// <summary>
/// Gets or sets pre-registered JsonConverters that automatically used by
/// serialization and deserialization methods.
/// </summary>
public static JsonConverterCollection RegisteredJsonConverters { get { return _registeredJsonConverters; } }

// ...
}
```

2.Insert the following codes to the "final" serialization/deserialization methods just before calling jsonSerializer.Serialize or jsonSerializer.Deserialize:
- private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
- public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
```
var jsc = jsonSerializer.Converters;
for (var i = 0; i < _registeredJsonConverters.Count; ++i)
{
var jc = _registeredJsonConverters[i];
if (!jsc.Contains(jc))
jsc.Insert(jsc.Count, jc);
}
```

3.Usage:
Register a custom JsonConverter
```
public class TreeNode<T>
{
static TreeNode()
{
JsonConvert.RegisteredJsonConverters.Add(new TreeNodeJsonConverter());
}
// ...
}
```

Use it!
```
var t = new TreeNode<T>();
var json = JsonConvert.SerializeObject(t); //need not to pass a converter any more!

// ...

var t = JsonConvert.DeserializeObject<Tree<T>>(json); //need not to pass a converter any more!
```

New Post: Error System.OutOfMemoryException in serialize big data

$
0
0
I'm trying to serialize to file a list objects with 190,000 records. The problem is when you try to do this, it gives the error:

System.OutOfMemoryException

My code:
File.WriteAllText("C:\\test.json", JsonConvert.SerializeObject(users));
how to do this? Is it a limit of Json.Net

Created Unassigned: ReadOnly object property not deserialized [25847]

$
0
0
I have an object with a ReadOnly property of complex object type. Its object is fully decorated for Newtonsoft serialization, and serialization works fine. On deserialization, I expect the values of Inner to be streamed into the existing instance. But this is not happening--the ReadOnly property is not even accessed during deserialization. I added a dummy read/write property as outlined in the second code below, and in that case, the Set is being invoked during deserialization, but it is passing in a new instance of Inner, not trying to serialize into the existing instance.

Is this a bug, or am I doing something wrong?

Get ObjectSecurity is NOT accessed during deserialization:
```
<Serializable(), JsonObject(MemberSerialization:=MemberSerialization.OptIn)> _
Public Class Outer

<JsonProperty("objectSecurity", ObjectCreationHandling:=ObjectCreationHandling.Reuse)> _
Public ReadOnly Property ObjectSecurity As Inner Implements ISecurable.ObjectSecurity
Get
Return _ObjectSecurity ' THIS IS NOT ACCESSED DURING DESERIALIZATION
End Get
End Property

[JsonObject(MemberSerialization=MemberSerialization.OptIn)]
public class Inner
{
[JsonProperty("objectId")]
public int ObjectID { get; set; }

```
With these changes, the j_ObjectSecurity Setter is invoked with a new instance of Inner, violating the request to Reuse the instance:

...
Public ReadOnly Property ObjectSecurity As Inner Implements ISecurable.ObjectSecurity
Get
Return _ObjectSecurity
End Get
End Property

<JsonProperty("objectSecurity", ObjectCreationHandling:=ObjectCreationHandling.Reuse)> _
Private Property j_ObjectSecurity As Inner
Get
Return _ObjectSecurity
End Get
Set(value As ObjectSecurityPermissions)
If value Is Nothing Then Throw New ArgumentNullException("ObjectSecurity")
' NOTE: the value instance here is a NEW instance of Inner, not the existing instance
_ObjectSecurity.Assign(value)
End Set
End Property
...

Created Unassigned: [JValue] Reference to type 'System.IConvertible' not found [25853]

$
0
0
There seems to be some compile-time warning when using JValue in Windows Phone 8.1 application (Windows Store) in Visual Studio 2013. Whenever using the constructor of JValue, I get warning:

"Warning 1
Reference to type 'System.IConvertible' claims it is defined in 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\WindowsPhoneApp\v8.1\mscorlib.dll', but it could not be found
c:\...\App2\packages\Newtonsoft.Json.6.0.6\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll"

To reproduce:
1. In Visual Studio 2013 create new project for Windows Phone 8.1 (Store one, not Silverlight). For example "Blank app (Windows Phone)"
2. Anywhere in any of the methods of the code-behind for a page, add
``` C#
new JValue(string.Empty)
```
3. Rebuild the project and observe the error

Created Unassigned: null value deserialization issue [25864]

$
0
0
In deserialization the __DefaultValueHandling.Populate__ hasn't any affect when used with the __NullValueHandling.Ignore__.

```
class Program
{
static void Main(string[] args)
{
var test = JsonConvert.DeserializeObject<Test>("{\"IntValue\":null}");
Console.WriteLine("IntValue:{0}", test.IntValue);
}
}

class Test
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(6)]
public int IntValue { get; set; }
}
```

Actual result is:
__IntValue:0__

Desired result is:
__IntValue:6__
Viewing all 1767 articles
Browse latest View live


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