jamesnk / newtonsoft.json Goto Github PK
View Code? Open in Web Editor NEWJson.NET is a popular high-performance JSON framework for .NET
Home Page: https://www.newtonsoft.com/json
License: MIT License
Json.NET is a popular high-performance JSON framework for .NET
Home Page: https://www.newtonsoft.com/json
License: MIT License
When building using the 3.5 project file, JsonSerializerInternalReader.cs fails to compile because of a using System.Numerics;
directive, and .NET 3.5 does not support this namespace.
[TestFixture]
public class JsonPropertyItemConverterType
{
public enum Thingy
{
Test
}
[JsonObject(MemberSerialization.OptIn)]
public abstract class Base
{
[JsonProperty(PropertyName = "type", Required = Required.Always, Order = 0,
ItemConverterType = typeof (StringEnumConverter))]
public Thingy Type { get; internal set; }
}
public class Thing : Base
{
public Thing()
{
Type = Thingy.Test;
}
}
[Test]
public void ItShouldWork()
{
var json = JsonConvert.SerializeObject(new Thing());
Assert.That(json, Is.EqualTo(@"{""type"":""Test""}"));
}
[Test]
public void ItShouldWork2()
{
var json = JsonConvert.SerializeObject(new Thing(), new StringEnumConverter());
Assert.That(json, Is.EqualTo(@"{""type"":""Test""}"));
}
}
In Json.NET 4.0 Release 8 "JsonConvert.DeserializeObject(string.Empty)" will return null,but in Json.NET 4.5 Release 1 "JsonConvert.DeserializeObject(string.Empty)" will throw an NullReferenceException...
The example in the documentation here no longer works.
It says I should get:
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0
// }
Instead I get:
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0,
// "Paid": false
// }
If this is not a bug, then could we have another option so I don't have to add "DefaultValue(false)" to all my booleans?
Here is a failing test case:
public class Invoice2
{
public string Company { get; set; }
public decimal Amount { get; set; }
// false is default value of bool
public bool Paid { get; set; }
// null is default value of nullable
public DateTime? PaidDate { get; set; }
public int anInt { get; set; }
}
[Test]
public void DefaultValueHandlingWithoutAttribute()
{
var invoice = new Invoice2();
var setting = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };
string json = JsonConvert.SerializeObject(invoice, Formatting.Indented, setting);
Assert.AreEqual("{}", json); ;
}
I have the following settings in my Global.asax.cs file
configuration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling
= DefaultValueHandling.Include;
configuration.Formatters.JsonFormatter.SerializerSettings.Formatting
= Formatting.Indented;
With 4.5.8 version of Newtonsoft.Json libary i got this data with my ApiController:
{ "Id": 11, "Content": "iPhone 4S", "Type": 0, "DateCreated": "2012-09-28T21:29:41.117", "DateUpdated": "2012-09-29T17:23:59.303", "IsArchived": false, "IsPublished": false, "TypeValue": 0 }
But with 4.5.9 or 4.5.10 version - i can't get default values in my JSON-serialized data (settings left the same):
{ "Id": 11, "Content": "iPhone 4S", "DateCreated": "2012-09-28T21:29:41.117", "DateUpdated": "2012-09-29T17:23:59.303" }
I'm using json.net to deserialize a datetimeoffset, but it is ignoring the specified timezone and converting the datetime to the local offset. For example, given
var content = @"{""startDateTime"":""2012-07-19T14:30:00+09:30""}";
When deserialized using:
var jsonSerializerSettings = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind };
var obj = JsonConvert.DeserializeObject(content, jsonSerializerSettings);
The obj will contain a property containing a DateTimeOffset but the value will be 2012-07-19T15:30:00+10:30 i.e. converted to the local timezone instead of preserving the original timezone.
Is there a way to get the value to be parsed as expected so that the resulting DateTimeOffset property will match the supplied value?
Hey, I was wondering if this feature is feasible, we would like the ability to configure the special $type property to use a different keyword as the property name, e.g. __type
The text "Wed, 18 Apr 2012 01:10:53 +0000" was parsed as a JTokenType.String instead of a JTokenType.Date.
Repro:
var twitterDataSnippet = "{"created_at":"Wed, 18 Apr 2012 01:10:53 +0000","from_user":"xyz"}";
JToken jv = JToken.Parse(twitterDataSnippet);
Console.WriteLine(jv.ToString());
JToken jtoken = jv.SelectToken("created_at");
Console.WriteLine(jtoken.Type);
var createdDate = (DateTime) jtoken;
Result:
Unhandled Exception: System.ArgumentException: Can not convert String to DateTime.
at Newtonsoft.Json.Linq.JToken.op_Explicit(JToken value) in c:\Dev\Releases\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Linq\JToken.cs:line 652
at ConsoleApplication2.Program.Main(String[] args) in Z:\personal\maying\UpgradingAnExistingMVC3App\ConsoleApplication2\Program.cs:line 20
Not sure the CodePlex Issue Tracker is being used any more, so logging here as well. Check out the issue here: https://json.codeplex.com/workitem/24162
Since upgrading to 5.0, I now receive a "This operation is only valid on generic types" exception when serializing. The complete stack trace is:
Exception: System.InvalidOperationException
Message: This operation is only valid on generic types.
Source: mscorlib
at System.RuntimeType.GetGenericTypeDefinition()
at Newtonsoft.Json.Serialization.JsonArrayContract..ctor(Type underlyingType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateArrayContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
Looking back at version 4.5 source, in JsonArrayContract.cs, there were checks for IsGenericType() which seem to be missing in the current version.
Hey, I was making some modifications to JSON.Net and saw an odd file in the unit tests project
The file in question is PoisonText.txt in the root of the Newtonsoft.Json.Tests project, and seems to contain spam links and some what I'm guessing is browser malware, here is a link to the file:
https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json.Tests/PoisonText.txt
This test fails:
[TestFixture]
public class JsonPropertyItemConverterType {
public class MyConverter : JsonConverter {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
writer.WriteValue("X");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
reader.ReadAsString();
return "X";
}
public override bool CanConvert(Type objectType) {
return true;
}
}
public class MyType {
[JsonProperty(ItemConverterType = typeof(MyConverter))]
public Dictionary<string, object> MyProperty { get; set; }
}
[Test]
public void ItShouldWork() {
var actual = JsonConvert.DeserializeObject<MyType>("{ \"MyProperty\":{\"Key\":\"Y\"}}");
Assert.That(actual.MyProperty["Key"], Is.EqualTo("X"));
}
}
and when run in the debugger, no breakpoints inside the MyConverter class are hit (but if I add a default constructor, a breakpoint inside that will be hit).
While serializing an object tree to a large (1.8GB) file, a profiler determined that JsonTextWriter.WriteIndent() was responsible for 13% of the run time.
Can't open solution "Newtonsoft.Json.sln":
Error opening project: "The project file could not be loaded. Could not find file..."
Missing project file from source:
Newtonsoft.Json-master\Src\Newtonsoft.Json\Newtonsoft.Json.csproj
Because of a question on SO, I went to investigate how does async work in JSON.NET. When I looked at the code (specifically JsonConvert.cs), I noticed that the async methods (like SerializeObjectAsync()
) just call the synchronous version using Task.Factory.StartNew()
.
This is generally not a good idea, because Async
methods are usually more scalable than their synchronous version, but this isn't true for your implementation. For more information (and a better explanation), see Stephen Toub's article Should I expose asynchronous wrappers for synchronous methods?
Because of that, I think you should remove the Async versions of your methods from the library.
Where adding Async
versions would make sense is when working with streams, but doing so would require a lot of changes in classes like JsonTextReader
(and I'm not sure how to do it without duplicating a lot of code in a way that doesn't break JSON.NET for older versions of .Net).
I saw that JsonSerializerInternalReader.CreateDynamic method does not take in account the JsonConstructor attribute. Can this be fixed ? (I can fix it my self if I am allowed to commit).
Refers to issue: http://json.codeplex.com/workitem/23558
Kind Regards,
Axente Adrian
Not sure if this happens on the RC but my Metro Style Application fails to build when using Json.NET 4.5.7. Here is the error:
Error 1 Loading assembly "c:\users\dfowler\documents\visual studio 11\Projects\Application4\packages\Newtonsoft.Json.4.5.7\lib\winrt45\Newtonsoft.Json.dll" failed. System.TypeLoadException: Could not load type 'System.Runtime.CompilerServices.CompilationRelaxationsAttribute' from assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
at System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit)
at Microsoft.Build.Tasks.ProcessResourceFiles.CheckAssemblyCultureInfo(String name, AssemblyName assemblyName, CultureInfo culture, Assembly a, Boolean mainAssembly)
at Microsoft.Build.Tasks.ProcessResourceFiles.ReadAssemblyResources(String name) Application1
I'm sure this worked with an earlier version. Did something break recently?
*** Edit ***
Not really an issue, since the converter is using Tokens etc, hence putting the contract resolver aside: but what is the proper way of adding members for serialization only?
//Dan
*** //Edit ***
If you crate a simple custom converter that adds a new property similar to this sample "http://james.newtonking.com/projects/json/help/index.html?topic=html/ContractResolver.htm"
the camel casing will not be applied if you use settings like these:
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new CouchbaseDocumentJsonConverter() },
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
E.g of custom converter:
public class FooJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var token = JToken.FromObject(value);
if (token.Type == JTokenType.Object)
{
var o = (JObject) token;
o.AddFirst(new JProperty("foo", "bar"));
o.WriteTo(writer);
}
else
token.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotSupportedException("This custom converter only supportes serialization and not deserialization.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
When used it will produce JSON like this:
{"foo":"bar","Name":"Daniel Wertheim"}
Sample usage:
var p = new Person
{
Name = "Daniel Wertheim",
};
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new FooJsonConverter() },
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(p, settings);
Expected result would be:
{"foo":"bar","name":"Daniel Wertheim"}
//Daniel
We use this in SignalR to convert method parameters.
token.ToObject(type)
Missing DateParseHandling in Portable csproj file.
This method allocates a new string each time:
This method should not allocate a char[] so often:
The git repository on github doesn't contain any tags. Is this on purpose or have you simply not executed git push --tags yet?
The git tags would be very useful else you don't know which release is which commit.
best regards,
Mirco
The following code should describe the mistake
[Test]
public void Issue() {
var serializedObject = JsonConvert.SerializeObject(new Dictionary<string[], Type>
{
{new[] {"hello", "world"}, null}
});
// A Dictionary with an Array/ List/ IEnumerable<>/ ICollection<> etc as key is not serialized correctly
// the code above produces the following json {"String[]-Array":null}
Assert.DoesNotThrow(() => JsonConvert.DeserializeObject(serializedObject, typeof (Dictionary<string[], Type>)));
}
I am pulling stable code from your repository based on tags, but the most recent tag is 4.5.9 and the most recent official release is 4.5.11. Is there any way that I can get you to add tags for each release? :-)
When object that is created with a non-default constructor and reference-resolving is used (with the default reference resolver), an exception is thrown in Serializer.ReferenceResolver.AddReference function: duplicate first or second (from the underlying bidirectional dictionary obviously).
For the created object, ReferenceResolver.AddReference is in fact invoked twice:
Not sure if the Add in CreateObjectFromNonDefaultConstructor can simply be removed (guess it's there for a reason).
Workaround: don't use non-default constructors ^^
Hi
The following test shows what might be a bug:
[TestFixture]
public class FallbackToCaseInsensitiveFailsForThisCaseTest
{
[Test]
public void CanSerializerAndDeserializeToAndFromFieldWithGetterOfOtherType()
{
var serializer = new JsonSerializer()
{
ContractResolver = new CR(),
TypeNameHandling = TypeNameHandling.All
};
var stringBuilder = new StringBuilder();
var textWriter = new StringWriter(stringBuilder);
serializer.Serialize(textWriter, new SomethingWithAList());
var stringReader = new StringReader(textWriter.ToString());
var jsonTextReader = new JsonTextReader(stringReader);
serializer.Deserialize<SomethingWithAList>(jsonTextReader);
}
public class CR : DefaultContractResolver
{
public CR()
: base(true)
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
}
}
public class SomethingWithAList
{
readonly List<int> ints = new List<int>();
public IEnumerable<int> Ints
{
get { return ints.Where(x => x > 10); }
}
}
}
Would it be possible to make an option to disable the case insensitive property name match?
Regards, Asger
var result = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
list = new double[]
{
double.NaN
}
});
Results in {"list":[NaN]}
which cannot be parsed by the JSON library used by browsers.
This appears to be a known issue with JSON parsers due to the nature of NaN...
The Newtonsoft Converter doesn't appear to have a problem reading NaN.
During the serialization of a self referencing object I received a JsonSerializationException. The error is:
{"Self referencing loop detected for type
'System.Collections.Generic.List`1[RavenDbTest.Category]'."}
The class that I try to serialize is the following:
[JsonObject( IsReference = true )]
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public Category Parent { get; set; }
public IList Children { get; set; }
public Category()
: base()
{
Children = new List();
}
public void Add( Category category )
{
category.Parent = this;
Children.Add( category );
}
public override Boolean Equals( Object obj )
{
return true;
}
}
The problem arise when I override the Equals method in a way that return always true.
After a little of digging in the code seems that the problem is in JsonSerializerInternalWriter at row 226. The code is:
if (_serializeStack.IndexOf(value) != -1)
{ ... }
if the 'value' object override the Equals method in a not conventional way (as in my example) the condition may assume a true value when instead it should be false.
A possible solution can be to substitute the code with something similar to the following:
if (_serializeStack.Any( o => Object.ReferenceEquals( o, value) ) )
{ ... }
If a type has an IList<> property, Json.NET will use List<> as the implementation when deserializing. Similarly, if a type has an ISet<> property, the default implementation should be HashSet<>.
Unexpected token when deserializing object: EndArray. Line 1, position 1706 using the TwitterAPI.
Returned JSON it fails on:
[{"coordinates":null,"created_at":"Sat Mar 10 06:44:44 +0000 2012","id_str":"178370788997595136","in_reply_to_status_id":null,"favorited":false,"geo":null,"truncated":false,"in_reply_to_status_id_str":null,"user":{"id":520080564,"notifications":false,"profile_sidebar_fill_color":"DDEEF6","statuses_count":1,"lang":"en","url":null,"time_zone":null,"created_at":"Sat Mar 10 04:18:29 +0000 2012","profile_background_image_url_https":"https://si0.twimg.com/images/themes/theme1/bg.png","utc_offset":null,"profile_background_color":"C0DEED","default_profile":true,"name":"Cosmo Sex School","verified":false,"contributors_enabled":false,"profile_background_image_url":"http://a0.twimg.com/images/themes/theme1/bg.png","location":null,"protected":false,"geo_enabled":false,"profile_link_color":"0084B4","following":false,"listed_count":0,"show_all_inline_media":false,"profile_use_background_image":true,"description":null,"friends_count":0,"id_str":"520080564","profile_text_color":"333333","profile_image_url_https":"https://si0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png","screen_name":"0xd3adbe3f","profile_sidebar_border_color":"C0DEED","follow_request_sent":false,"default_profile_image":true,"profile_image_url":"http://a0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png","is_translator":false,"followers_count":0,"favourites_count":0,"profile_background_tile":false},"retweet_count":0,"in_reply_to_user_id_str":null,"entities":{"hashtags":[],"user_mentions":[],"urls":[]},"place":null,"retweeted":false,"source":"web","contributors":null,"id":178370788997595136,"in_reply_to_screen_name":null,"in_reply_to_user_id":null,"text":"test"}]
The default value for a Guid isn't null like it is for most objects. It's actually Guid.Empty. My guess is that that's the reason why the serializer doesn't ignore the default value.
Example property:
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public Guid owner { get; set; }
Consider the following code:
public class SerializableContractResolver : DefaultContractResolver
{
public SerializableContractResolver()
{
this.IgnoreSerializableAttribute = false;
}
}
var tuple = Tuple.Create(500);
var json = JsonConvert.SerializeObject(tuple, new JsonSerializerSettings() { ContractResolver = new SerializableContractResolver() });
Console.WriteLine(json);
var obj = JsonConvert.DeserializeObject<Tuple<int>>(json, new JsonSerializerSettings() { ContractResolver = new SerializableContractResolver() });
Console.WriteLine(obj.Item1);
Contract.Assert(obj.Item1 == 500);
The assertion fails. Serialization seems to be working fine but deserialization isn't setting the fields properly. Tuple is a [Serializable] type.
When deserializing class with XElement property, if this property is null, Exception will be thrown.
Fixed by changing XmlNodeConverter:
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
Test case:
class NullableXml
{
public string Name;
public XElement notNull;
public XElement isNull;
}
[TestMethod]
public void SerializeAndDeserializeNullableXml()
{
var xml = new NullableXml { Name = "test", notNull = XElement.Parse("<root>test</root>") };
var json = JsonSerializer.Serialize(xml);
var w2 = JsonSerializer.Deserialize<string, NullableXml>(json);
Assert.AreEqual(xml.Name, w2.Name);
Assert.AreEqual(xml.isNull, w2.isNull);
Assert.AreEqual(xml.notNull.ToString(), w2.notNull.ToString());
}
If you have two classes one inheriting from the other, If you place a shouldserialize method on the derivied class for a property of the base class it does not work. Digging in the code, when it sees the property, it sees it as a member of the base class therefore it doesn't call the method on the derived type. Do you think this is a limitation of reflection or something that the library could benefit from?
Expanding on ConditionalPropertiesTests.cs
public class NewEmployee : Employee
{
public int Age { get; set; }
public bool ShouldSerializeName()
{
return false;
}
}
[Test]
public void ShouldSerializeInheritedClassTest()
{
#region ShouldSerializeClassTest
NewEmployee joe = new NewEmployee();
joe.Name = "Joe Employee";
joe.Age = 100;
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
string json = JsonConvert.SerializeObject(joe, Formatting.Indented);
// {
// "Manager": {
// "Name": "Mike Manager"
// },
// "Age": 100
// }
#endregion
Assert.AreEqual(@"{
""Age"": 100,
""Manager"": {
""Name"": ""Mike Manager""
}
}", json);
}
}
sorry i don't know a better way to attach this wihtout a pull request.
For example, we have
string json = @"
{
'company': {
'name': 'abc',
'address': 'summer street'
}
}";
JObject j = JObject.Parse(json);
JObject c = (JObject)j["customer"];
if (c != null)
{
string name = (string)c["name"];
}
this works fine because (JObject) j["customer"] will return null;
However
string json = @"
{
'company': {
'name': 'abc',
'address': 'summer street'
},
'customer': null
}";
JObject j = JObject.Parse(json);
JObject c = (JObject)j["customer"];
if (c != null)
{
string name = (string)c["name"];
}
will throw an InvalidCastException with error message:
Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'
Is it a good idea to add an explicit cast operator to handle this kind of situation? since JObject is JToken also and is nullable.
Thanks,
I just got JSON.Net for Silverlight from NuGet (version 4.5.5.14908), but I can't build because the dll isn't signed with a strong name. The net40 is (according to the command line sn.exe and http://james.newtonking.com/archive/2012/04/04/json-net-strong-naming-and-assembly-version-numbers.aspx).
I'll download the source and re-sign it myself for now.
Thanks,
Kevin
Here's some history:
And here's some thoughts:
One possible fix is to remove references to LinqBridge assembly and use LinqBrige from Json.NET. But we can't do it since Enumerable class made Internal (while in LinqBridge it is public).
So we can't remove reference to LinqBrige as we want to use Linq, and we can't use LinqBridge with Json.NET since there's an ambiguous reference to types like Action and Func.
Something should be done... it can be:
What is the preferred way to do it? Why have you removed reference to LinqBridge and included LinqBridge as a source file?
When using Date in ISO 8601, IE and Safari cannot parse the Date string with two digits after the dot (milisecond) but three digit value is ok.
IE, Safari:
new Date('2012-08-01T04:20:20.29Z') -> Invalid Date
new Date('2012-08-01T04:20:20.290Z') -> Ok
and the Json.net serializer just generates value with two digits if then milisecond end with zero (like 290, 200,..)
How could I solve this problem?
Please help.
The PCL project reference some unuseful library.
Below a snippet code from Newtonsoft.Json.Portable.csproj:
So, it must to remove these references to use Json.Portable dll from an other PCL project.
When serializing numeric properties of classes that, for example, divide by zero, the result is NaN, breaking the JSON output.
{ "InvalidCalculatedProperty" : NaN }
I'd recommend switching to string type in this case:
{ "InvalidCalculatedProperty" : "NaN" }
...or, perhaps, throwing an exception.
Anything else, but the current output isn't valid.
Thank you for this amazing library. Keep up the great work. Cheers! -Jonathan
Console.WriteLine(((IDictionary<string, JToken>)new JObject()).Keys);
will give you a NullRef
There is a little Issue when converting a JToken that holds an Int to a bool, because System.Convert.ChangeType gives back true on numbers greater than 0 and false on 0, but I think that is not the right way to behave with this.
You should see if you want to cast a int to a bool and give false back then. Otherwise you can give the System.Convert back.
What is your opinion? Btw. It's Linq/Extension.cs:238 and following.
My way around this is the following atm.
if(token.Type == JTokenType.Integer && typeof(T) == typeof(bool))
else
I'm not sure this is currently supported but I'd like to deserialize multiple unrelated JSON objects from a string where objects are separated by whitespace. Because of my specific use case I cannot reliably transform the input to say a JSON array and deserialize that.
The following test demonstrates the desired behavour.
using Newtonsoft.Json;
using NUnit.Framework;
using System.IO;
namespace Tests {
[TestFixture]
public class SerializerTest {
[Test]
public void ReadManyObjectFromTextReader() {
var reader = new StringReader("1 2 3");
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
Assert.AreEqual(1, serializer.Deserialize(jsonReader, typeof(int)));
Assert.AreEqual(2, serializer.Deserialize(jsonReader, typeof(int)));
Assert.AreEqual(3, serializer.Deserialize(jsonReader, typeof(int)));
}
}
}
Instead of deserializing the expected 1, 2, 3 I see 1, 1, 1 - all subsequent deserializations from the JsonTextReader returns the first value.
Repositories on GitHub should include ReadMe.md ("md" to enable markdown formatting) with basic information. Also, since this is now the primary repository, http://json.net and http://json.codeplex.com should link to GitHub source code instead of CodePlex (probably with CodePlex link left for "backward compatibility", as there're enough issues in the issue tracker).
I just tried to build Newtonsoft.Json on my laptop, which has an Italian WIndows 7 Professional. Even after commenting out all build descriptions except for .NET 4 in build.ps1 (I was getting an error while building the portable class library, but there's already an open issue for that), here's what I got:
229) Test Failure : Newtonsoft.Json.Tests.Utilities.DynamicReflectionDelegateFac
toryTests.CreateSetWithBadTarget
Unexpected exception message.
Expected: Specified cast is not valid.
Got: Cast specificato non valido.
String lengths are both 28. Strings differ at index 0.
Expected: "Specified cast is not valid."
But was: "Cast specificato non valido."
-----------^
in Newtonsoft.Json.Tests.ExceptionAssert.Throws[TException](String message, Acti
on action) in x:\3rdParty\Newtonsoft.Json\Src\Newtonsoft.Json.Tests\TestFixtureB
ase.cs:riga 132
in Newtonsoft.Json.Tests.Utilities.DynamicReflectionDelegateFactoryTests.CreateS
etWithBadTarget() in x:\3rdParty\Newtonsoft.Json\Src\Newtonsoft.Json.Tests\Utili
ties\DynamicReflectionDelegateFactoryTests.cs:riga 83
build.ps1:Error running Newtonsoft.Json.Tests tests
Needless to say, "Cast specificato non valido." is Italian for "Specified cast is not valid."
As we all know, DataContractSerializer and BinaryFormatter doesn't call the constructor.
Is it also possible to add this feature in Json.net?
I'm planning to change our serializer to Json.net but run into a compatibility issue since Json.net calls a constructor.
Yes, the DTO design is faulty but, I imagine that this feature may help others migrate too.
Please add support to converting JObject to another types, not only to string
For example, I need to get the data (number) as 4 bytes (uint). Faster will immediately convert the object in uint, than to convert a object to string to uint
We have a nasty classes looking like
HeadacheColleciton: IEnumerable<Headache> {
HeadacheColleciton(IEnumerable<Headache> source) { ... }
}
Don't ask why.
Currently JSON.NET does only look for suitable consttructor that creates an intermediate collection if the class implements ReadOnlyCollection<T>
(CollectionUtils.cs#L189)
Maybe there's a deep performance reason for this, but I cannot see why not testing for IEnumerable<T>
instead as a last resort, if other means of constructing the object fail.
The following code works for us under Win7 .NET 4.0 but when we tried it under MacOSX with Mono we got an exception?
string json = JsonConvert.SerializeObject(new ArgumentException());
ArgumentException ex = JsonConvert.DeserializeObject(json);
at Newtonsoft.Json.Serialization.JsonFormatterConverter.GetTokenValue (object) <0x00061>
at Newtonsoft.Json.Serialization.JsonFormatterConverter.ToString (object) <IL 0x00002, 0x0002f>
at System.Runtime.Serialization.SerializationInfo.GetString (string) [0x0001a] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/corlib/System.Runtime.Serialization/SerializationInfo.cs:369
at System.Exception..ctor (System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) [0x00022] in /private/tmp/monobuild/build/BUILD/mono-2.10.8/mcs/class/corlib/System/Exception.cs:90
at System.SystemException..ctor (System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) <IL 0x00003, 0x0004b>
at System.ArgumentException..ctor (System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) <IL 0x00003, 0x0004b>
at (wrapper dynamic-method) System.ArgumentException.Void .ctor(SerializationInfo, StreamingContext) (object,object[]) <IL 0x0002a, 0x00107>
at Newtonsoft.Json.Serialization.DefaultContractResolver/<>c__DisplayClassa.b__9 (object[]) <IL 0x00008, 0x0002e>
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable (Newtonsoft.Json.JsonReader,Newtonsoft.Json.Serialization.JsonISerializableContract,string) <IL 0x0010b, 0x00559>
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader,System.Type,Newtonsoft.Json.Serialization.JsonContract,Newtonsoft.Json.Serialization.JsonProperty,object) <IL 0x003eb, 0x0143b>
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader,System.Type,Newtonsoft.Json.Serialization.JsonContract,Newtonsoft.Json.Serialization.JsonProperty,object) <IL 0x00075, 0x00117>
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty (Newtonsoft.Json.JsonReader,System.Type,Newtonsoft.Json.Serialization.JsonContract,Newtonsoft.Json.JsonConverter) <IL 0x00024, 0x000e3>
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader,System.Type) <IL 0x00040, 0x0018b>
at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader,System.Type) <IL 0x00015, 0x00097>
at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader,System.Type) <IL 0x00003, 0x0002b>
at Newtonsoft.Json.JsonConvert.DeserializeObject (string,System.Type,Newtonsoft.Json.JsonSerializerSettings) <IL 0x00018, 0x000eb>
at Newtonsoft.Json.JsonConvert.DeserializeObject<System.ArgumentException> (string,Newtonsoft.Json.JsonSerializerSettings) <0x00047>
at Newtonsoft.Json.JsonConvert.DeserializeObject<System.ArgumentException> (string) <0x0004b>
at SeriDeSeri.MainClass.Main (string[]) [0x0000b] in /Users/klimm/Documents/dev/SeriDeSeri/Main.cs:11
Could you please try to reproduce our problem?
What solution for our problem do you propose?
Hi there,
I just compiled your excellent library for use with monodroid based on the wphone project, since I needed the actual version for serialization and SignalR. I wanted to ask You, how I can contribute the Monodroid Solution/Project, or if You do not want such a project type in your repository - I think it would be nice for others too.
Regards
Thomas
Lets imagine that we have Json string:
string jsonText =
"{\"Entity\":" +
"{\"Columns\":{" +
"\"Item1\":{\"C1\":\"1\"}, " +
"\"Item2\":{\"C2\":\"2\"}, " +
"\"Item3\":{\"C3\":\"3\"}}," +
"\"Indexes\":{" +
"\"Item4\":{\"K4\":\"4\", " +
"\"SubItem\":{\"H1\":\"0\"}}, " +
"\"Item5\":{\"K5\":\"5\"}}}";
While reading this string with different lib versions you will get JsonReader.Depth value for example at the end of "Item1" prop. And this is not the first time I get into this problem while trying to move to the new version of Json.NET.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.