JavaScriptSerializer: Object reference not set to an instance of an object - c#

What am I doing wrong here?
using System.Web.Script.Serialization;
string json = "{\"numbers\":[{\"one\":\"1\"},{\"two\":\"2\"},{\"three\":\"3\"}]}";
dynamic dictionary = new JavaScriptSerializer().Deserialize<dynamic>(json);
Assert.AreEqual(3, dictionary["numbers"].Count);
System.NullReferenceException : Object reference not set to an instance of an object
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToList (System.Collections.ArrayList col, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType[Object] (System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[Object] (System.String input) [0x00000] in <filename unknown>:0

As I see no problems with your code, apart from the use of the count property, and since the code is breaking when the json is being deserialized, I would advise you to use the static type definition instead, just to narrow the changes of problems with your code:
string json = "{\"numbers\":[{\"one\":\"1\"},{\"two\":\"2\"},{\"three\":\"3\"}]}";
var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
Maybe just maybe there is an issue with using dynamic types with the JavaScriptSerializer and if there is indeed a problem with the JavaScriptSerializer you can always report that to MSFT.

Since I could not make Dictionary<string, object> work, I've decided to drop it and use static types instead. BTW, this online tool is quite handy for generating C# classes from JSON.

Related

MongoDB not running on iOS Unity Build

Hi I am trying to query my Mongo Database by using a list of Facebook ID's as the parameter in order to return the list of users with corresponding accounts. The method works fine in the Unity Editor however when I run it on iOS I get a constructor error (I have set a blank default constructor in order to solve the issue however it still doesn't work)
Error
MissingMethodException: Method not found: 'Default constructor not found...ctor() of MongoDB.Driver.CommandResultSerializer'.
at System.Activator.CreateInstance (System.Type type, System.Object[] args) [0x00000] in <filename unknown>:0
at MongoDB.Bson.Serialization.Attributes.BsonSerializerAttribute.CreateSerializer (System.Type type) [0x00000] in <filename unknown>:0
at MongoDB.Bson.Serialization.BsonSerializer.LookupSerializer (System.Type type) [0x00000] in <filename unknown>:0
at MongoDB.Driver.MongoServerInstance.RunCommandAs[TCommandResult] (MongoDB.Driver.Internal.MongoConnection connection, System.String databaseName, IMongoCommand command) [0x00000] in <filename unknown>:0
at MongoDB.Driver.MongoServerInstance.Ping (MongoDB.Driver.Internal.MongoConnection connection) [0x00000] in <filename unknown>:0
at MongoDB.Driver.MongoServerInstance.Connect () [0x00000] in <filename unknown>:0
at MongoDB.Driver.Internal.DirectMongoServerProxy.Connect (TimeSpan timeout, MongoDB.Driver.ReadPreference readPreference) [0x00000] in <filename unknown>:0
at Tacticsoft.Examples.SimpleTableViewController.FriendsHighscoreHndlr (IGraphResult FBresult) [0x00000] in <filename unknown>:0
at Facebook.Unity.AsyncRequestString+<Start>c__Iterator0.MoveNext () [0x00000] in <filename unknown>:0
at UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) [0x00000] in <filename unknown>:0
Rethrow as MongoConnectionException: Unable to connect to server XXX.XXX.XX.XX:XXXX: Method not found: 'Default constructor not found...ctor() of MongoDB.Driver.CommandResultSerializer'..
at MongoDB.Driver.Internal.DirectMongoServerProxy.Connect (TimeSpan timeout, MongoDB.Driver.ReadPreference readPreference) [0x00000] in <filename unknown>:0
at Tacticsoft.Examples.SimpleTableViewController.FriendsHighscoreHndlr (IGraphResult FBresult) [0x00000] in <filename unknown>:0
at Facebook.Unity.AsyncRequestString+<Start>c__Iterator0.MoveNext () [0x00000] in <filename unknown>:0
at UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) [0x00000] in <filename unknown>:0
Initial Method
public void FetchData()
{
//data = Mongo.Instance.players.FindAll().ToList();
if (FB.IsLoggedIn)
{
FB.API("me/friends", HttpMethod.GET, FriendsHighscoreHndlr);
}
}
Callback Method
public void FriendsHighscoreHndlr (IGraphResult FBresult)
{
var dict = Json.Deserialize(FBresult.ToString()) as Dictionary<string,object>;
var friendList = new List<object>();
friendList = (List<object>)(dict["data"]);
int _friendCount = friendList.Count;
Debug.Log("Found friends on FB, _friendCount ... " +_friendCount);
List<string> friendIDsFromFB = new List<string>();
for (int i=0; i<_friendCount; i++) {
string friendFBID = getDataValueForKey( (Dictionary<string,object>)(friendList[i]), "id");
string friendName = getDataValueForKey( (Dictionary<string,object>)(friendList[i]), "name");
Debug.Log( i +"/" +_friendCount +" " +friendFBID +" " +friendName);
friendIDsFromFB.Add(friendFBID);
}
//friendIDsFromFB.Add(AccessToken.CurrentAccessToken.UserId);
var query = Query.In("facebookID", BsonArray.Create(friendIDsFromFB));
//Debug.Log(query);
data = Mongo.Instance.players.Find(query).ToList();
}
Data Value for Key Method
private string getDataValueForKey(Dictionary<string, object> dict, string key) {
object objectForKey;
if (dict.TryGetValue(key, out objectForKey)) {
return (string)objectForKey;
} else {
return "";
}
}
Return Query Result
{
"_id" : ObjectId("XXXXXX"),
"facebookID" : "XXXXXXXXXXXXXX",
"name" : "John Doe",
"highScore" : 40501
}

Accessing NetworkManager Connection Settings through dbus-sharp

I'm running Arch Linux with the following version of mcs:
>mcs --version
Mono C# compiler version 4.0.4.0
And the following version of dbus-sharp
>pacman -Ss dbus-sharp
extra/dbus-sharp 0.8.1-1 [installed] C# implementation of D-Bus
extra/dbus-sharp-glib 0.6.0-1 [installed] C# GLib implementation of D-Bus
This is my test program, based on the example code found here: https://gist.github.com/Ummon/4317268
I'm just trying to access the settings of the currently active connection, which should be returned as a 'Dict of {String, Dict of {String, Variant}}' as I've checked in the d-feet tool for the org.freedesktop.NetworkManager.Settings.Connection interface
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using DBus;
namespace NetworkManagerDictTest {
public class MyTest {
[Interface("org.freedesktop.NetworkManager.Settings.Connection")]
public interface IConnection {
IDictionary<string, IDictionary<string, object>> GetSettings();
}
readonly static string BUS_NAME = "org.freedesktop.NetworkManager";
public static void Main(string[] argv) {
org.freedesktop.DBus.Properties NetworkManagerProps = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, new ObjectPath("/org/freedesktop/NetworkManager"));
ObjectPath[] activeConnections = NetworkManagerProps.Get(BUS_NAME, "ActiveConnections") as ObjectPath[];
if (activeConnections.Length > 0) {
org.freedesktop.DBus.Properties ActiveConnectionProperties = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, activeConnections[0]);
ObjectPath ActiveConnectionPath = ActiveConnectionProperties.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") as ObjectPath;
Console.WriteLine("Using connection path: " + ActiveConnectionPath);
IConnection connection = Bus.System.GetObject<IConnection>(BUS_NAME, ActiveConnectionPath);
Console.WriteLine("Connection Object ok");
IDictionary<string, IDictionary<string, object>> settings = connection.GetSettings();
Console.WriteLine(settings);
}
}
}
}
Compilation went without errors nor warnings:
mcs Test.cs -r:/usr/lib/mono/dbus-sharp-2.0/dbus-sharp.dll -r:/usr/lib/mono/dbus-sharp-glib-2.0/dbus-sharp-glib.dll
However my program crashes during execution with the following output:
>mono Test.exe
Using connection path: /org/freedesktop/NetworkManager/Settings/0
Connection Object ok
Unhandled Exception:
DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
What can I do to work around this problem? Am I making a mistake when working with the DBus? It seems that all the method calls up to GetSettings went without issues. I've also encountered a similar problem while trying to fix a bug in another project where dbus-sharp would throw an exception when calling GetSettings. Could this be an issue of dbus-sharp instead?
Taking a look at the source code it seems that dbus-sharp infers the return type directly from the signature of the declared method. Unfortunately it doesn't check if I'm using a parent class or interface of Dictionary, eventually it tries to read a DBus struct because of a fallback case which causes the exception as DBus structs are 8 byte padded while dicts use 4 bytes
Replacing all the IDictionary types with Dictionary worked fine and solved my problem.

Does the Unity compiler not fully support named parameters?

The following code compiles just fine in Visual Studio, but in Unity (4.6.x) it creates a compiler error:
public class ErrorTest
{
void DoSomething(bool a = true, bool f = true) { }
void DoSomething(int b, bool f = true) { }
public void SomeMethod()
{
DoSomething(f: false);
}
}
The call to DoSomething is what makes the compiler choke. The question is why, there's really no ambiguity.
The console output when Unity chokes like this:
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: Mono.CSharp.InternalErrorException: Internal error
at Mono.CSharp.MethodGroupExpr.IsApplicable (Mono.CSharp.ResolveContext ec, Mono.CSharp.Arguments& arguments, Int32 arg_count, System.Reflection.MethodBase& method, System.Boolean& params_expanded_form) [0x00000] in <filename unknown>:0
at Mono.CSharp.MethodGroupExpr.OverloadResolve (Mono.CSharp.ResolveContext ec, Mono.CSharp.Arguments& Arguments, Boolean may_fail, Location loc) [0x00000] in <filename unknown>:0
at Mono.CSharp.Invocation.DoResolveOverload (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Invocation.DoResolve (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Expression.Resolve (Mono.CSharp.ResolveContext ec, ResolveFlags flags) [0x00000] in <filename unknown>:0
at Mono.CSharp.Expression.Resolve (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.ExpressionStatement.ResolveStatement (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.StatementExpression.Resolve (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Block.Resolve (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.ToplevelBlock.Resolve (Mono.CSharp.FlowBranching parent, Mono.CSharp.BlockContext rc, Mono.CSharp.ParametersCompiled ip, IMethodData md) [0x00000] in <filename unknown>:0
There was/is apparently a bug where combining the use of namespaces and default parameters caused an internal error like this. It was allegedly fixed in 4.5, but from the comments it has been allegedly fixed before. You might try eliminating the namespace declaration in your class as an experiment to see if that bug is what you're experiencing.

Newtonsoft on Mono 4.0

I am trying to execute a compiled application on Ubuntu and get this error:
Can't find custom attr constructor image: /root/Newtonsoft.Json.dll mtoken: 0x0a000077
Missing method System.Reflection.MethodInfo::CreateDelegate(Type) in assembly /usr/lib/mono/4.0/mscorlib.dll, referenced in assembly /root/Newtonsoft.Json.dll
Method not found: 'System.Reflection.MethodInfo.CreateDelegate'. at Newtonsoft.Json.Serialization.DefaultContractResolver.GetDefaultCreator (System.Type createdType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.InitializeContract (Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateLinqContract (System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.GetContractSafe (System.Object value) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonSerializer.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializer jsonSerializer) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value) [0x00000] in <filename unknown>:0
at Server.Misc.BalanceEconomy.InvokeMethod (System.String a_sMethod, System.Object[] a_params) [0x00000] in <filename unknown>:0
at Server.Misc.BalanceEconomy.RefreshBalances () [0x00000] in <filename unknown>:0
at Server.Misc.BalanceEconomy.OnTick () [0x00000] in <filename unknown>:0
How do I fix this?

Monotouch with Newtonsoft not working

I am very new to Monotouch/iOS development. I'm using
==========
MonoDevelop 2.8.8.4
Installation UUID: 0d3db625-7df9-4282-9aa6-177c25a46d07
Runtime:
Mono 2.10.9 (tarball Tue Mar 20 15:31:37 EDT 2012)
GTK 2.24.10
GTK# (2.12.0.0)
Mono for Android not installed
Apple Developer Tools:
Xcode 4.2.1 (834)
Build 4D502
Monotouch: 5.2.10 (Evaluation)
==========
I am trying to serialize object to json string using Newtonsoft 3.5 all.
Very simple code but not working.. Can anybody can please help me ...
partial void Action_Clicked (MonoTouch.Foundation.NSObject sender)
{
myDTO test = new myDTO();
string teststring = ObjToJSON(test);
}
public string ObjToJSON(myDTO oObject) //Old function name is ObjToJSON_WithWrapper
{
string sJSON = "";
sJSON = Newtonsoft.Json.JsonConvert.SerializeObject(oObject);
return sJSON;
}
public myDTO JSONToObj(String JSONString) //Old function name is JSONToObjNew
{
myDTO deseri = JsonConvert.DeserializeObject<myDTO>(JSONString);
return deseri;
}
public class myDTO
{
public myDTO()
{
}
public string StringObject {get; set;}
}
Above is my simple test code but it's giving me error when it's run Newtonsoft.Json.JsonConvert.SerializeObject(oObject);
*** ERROR***
{System.TypeLoadException: A type load exception has occurred.
at Newtonsoft.Json.Utilities.ThreadSafeStore`2[System.Type,System.Type].AddValue System.Type key) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Utilities.ThreadSafeStore`2[System.Type,System.Type].Get (System.Type key) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonTypeReflector.GetAssociatedMetadataType (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonTypeReflector.GetAttribute[JsonContainerAttribute] (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonTypeReflector.GetAttribute[JsonContainerAttribute] (ICustomAttributeProvider attributeProvider) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Utilities.ThreadSafeStore`2[System.Reflection.ICustomAttributeProvider,Newtonsoft.Json.JsonContainerAttribute].AddValue (ICustomAttributeProvider key) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Utilities.ThreadSafeStore`2[System.Reflection.ICustomAttributeProvider,Newtonsoft.Json.JsonContainerAttribute].Get (ICustomAttributeProvider key) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.CachedAttributeGetter`1[Newtonsoft.Json.JsonContainerAttribute].GetAttribute (ICustomAttributeProvider type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonTypeReflector.GetJsonContainerAttribute (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonTypeReflector.GetJsonObjectAttribute (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract (System.Type type) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.GetContractSafe (System.Object value) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonSerializer.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, Formatting formatting, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0
at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value) [0x00000] in <filename unknown>:0
at JSONTest1.JSONTest1ViewController.ObjToJSON (JSONTest1.myDTO oObject) [0x00006] in /Users/developer/Projects/JSONTest1/JSONTest1/JSONTest1ViewController.cs:61
at JSONTest1.JSONTest1ViewController.Action_Clicked (MonoTouch.Foundation.NSObject sender) [0x00006] in /Users/developer/Projects/JSONTest1/JSONTest1/JSONTest1ViewController.cs:52 at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
at JSONTest1.Application.Main (System.String[] args) [0x00000] in /Users/developer/Projects/JSONTest1/JSONTest1/Main.cs:17 }
You need this version of Newtonsoft for MonoTouch:
https://github.com/ayoung/Newtonsoft.Json

Categories

Resources