Serialize an object using Newsofton.Json in C#

Hi everyone! I’m implementing a skinmenu in C# from scratch and everything is going well. The only thing I can’t do is serialize an object into JSON.

C# object example: Dictionary<string, Dictionary<string, int[]>>

JSON example:

{
  "string": {
    "key1": [0, 1, 2, 3],
    "key2": [4, 5, 6, 7]
  }
}

In particular, when calling the JsonConvert.SerializeObject() method from the Newtonsoft.Json library, an enormous error trace is released, reported below:

[   1769875] [    GTAProcess]             MainThrd/ Creating script environments for skinmenu
[   1770047] [    GTAProcess]             MainThrd/ Loaded resource.Client.net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null into ScriptDomain_2104012043
[   1770078] [    GTAProcess]             MainThrd/ Instantiated instance of script resource.Client.ClientMain.
[   1770078] [    GTAProcess]             MainThrd/ OnConnectionProgress: Mounted skinmenu (1 of 1)
[   1774968] [    GTAProcess]             MainThrd/ Could not load assembly Newtonsoft.Json - loading exceptions: Exception loading assembly Newtonsoft.Json: System.IO.FileNotFoundException: Unable to find the specified file.

[   1774968] [    GTAProcess]             MainThrd/   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR (System.Int32 errorCode) [0x0000a] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774968] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager+DirectScriptHost.OpenHostFileInternal (System.String fileName) [0x00011] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:726 
[   1774968] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager+DirectScriptHost.OpenHostFile (System.String fileName) [0x00000] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:712 
[   1774968] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.LoadAssemblyInternal (System.String baseName, System.Boolean useSearchPaths) [0x00075] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:212 
[   1774968] [    GTAProcess]             MainThrd/ Exception loading assembly Client/bin/Release/net452/publish/Newtonsoft.Json: System.BadImageFormatException: 
[   1774968] [    GTAProcess]             MainThrd/   at (wrapper managed-to-native) System.AppDomain:LoadAssemblyRaw (System.AppDomain,byte[],byte[],System.Security.Policy.Evidence,bool)
[   1774968] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence, System.Boolean refonly) [0x0000e] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774968] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774968] [    GTAProcess]             MainThrd/   at (wrapper remoting-invoke-with-check) System.AppDomain:Load (byte[],byte[],System.Security.Policy.Evidence)
[   1774968] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774968] [    GTAProcess]             MainThrd/   at (wrapper remoting-invoke-with-check) System.AppDomain:Load (byte[],byte[])
[   1774968] [    GTAProcess]             MainThrd/   at System.Reflection.Assembly.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore) [0x00005] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774968] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.CreateAssemblyInternal (System.String assemblyFile, System.Byte[] assemblyData, System.Byte[] symbolData) [0x0003c] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:129 
[   1774968] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.LoadAssemblyInternal (System.String baseName, System.Boolean useSearchPaths) [0x00177] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:251 
[   1774968] [    GTAProcess]             MainThrd/ 
[   1774984] [    GTAProcess]             MainThrd/ Could not load assembly Newtonsoft.Json - loading exceptions: Exception loading assembly Newtonsoft.Json: System.IO.FileNotFoundException: Unable to find the specified file.
[   1774984] [    GTAProcess]             MainThrd/   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR (System.Int32 errorCode) [0x0000a] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager+DirectScriptHost.OpenHostFileInternal (System.String fileName) [0x00011] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:726 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager+DirectScriptHost.OpenHostFile (System.String fileName) [0x00000] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:712 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.LoadAssemblyInternal (System.String baseName, System.Boolean useSearchPaths) [0x00075] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:212 
[   1774984] [    GTAProcess]             MainThrd/ Exception loading assembly Client/bin/Release/net452/publish/Newtonsoft.Json: System.BadImageFormatException: 
[   1774984] [    GTAProcess]             MainThrd/   at (wrapper managed-to-native) System.AppDomain:LoadAssemblyRaw (System.AppDomain,byte[],byte[],System.Security.Policy.Evidence,bool)
[   1774984] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence, System.Boolean refonly) [0x0000e] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at (wrapper remoting-invoke-with-check) System.AppDomain:Load (byte[],byte[],System.Security.Policy.Evidence)
[   1774984] [    GTAProcess]             MainThrd/   at System.AppDomain.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at (wrapper remoting-invoke-with-check) System.AppDomain:Load (byte[],byte[])
[   1774984] [    GTAProcess]             MainThrd/   at System.Reflection.Assembly.Load (System.Byte[] rawAssembly, System.Byte[] rawSymbolStore) [0x00005] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.CreateAssemblyInternal (System.String assemblyFile, System.Byte[] assemblyData, System.Byte[] symbolData) [0x0003c] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:129 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.InternalManager.LoadAssemblyInternal (System.String baseName, System.Boolean useSearchPaths) [0x00177] in C:\gl\builds\master\fivem\code\client\clrcore\InternalManager.cs:251 
[   1774984] [    GTAProcess]             MainThrd/ 
[   1774984] [    GTAProcess]             MainThrd/ Error invoking callback for event giveSkinMenu: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.BadImageFormatException: Error verifying resource.Client.ClientMain:GiveSkinMenu (int): Cannot load method from token 0x0a00002f for call at 0x0035
[   1774984] [    GTAProcess]             MainThrd/   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
[   1774984] [    GTAProcess]             MainThrd/   at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <4a74a468ceae4b8199f7400d96d8dff5>:0 

[   1774984] [    GTAProcess]             MainThrd/    --- End of inner exception stack trace ---
[   1774984] [    GTAProcess]             MainThrd/   at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00048] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at System.Delegate.DynamicInvokeImpl (System.Object[] args) [0x000e7] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at System.MulticastDelegate.DynamicInvokeImpl (System.Object[] args) [0x00008] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at System.Delegate.DynamicInvoke (System.Object[] args) [0x00000] in <4a74a468ceae4b8199f7400d96d8dff5>:0 
[   1774984] [    GTAProcess]             MainThrd/   at CitizenFX.Core.EventHandlerEntry+<Invoke>d__5.MoveNext () [0x00064] in C:\gl\builds\master\fivem\code\client\clrcore\EventHandlerDictionary.cs:107 

This is my .csproj:

<Project Sdk="CitizenFX.Sdk.Client/0.2.3">
    <PropertyGroup>
      <TargetFramework>net452</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <Compile Include="../Shared/**/*.cs" />
    </ItemGroup>
    <ItemGroup>
      <PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
    </ItemGroup>
    <ItemGroup>
      <PackageReference Update="CitizenFX.Core.Client" Version="1.0.6256" />
    </ItemGroup>
</Project>

The ClientMain.cs:

....

public void GiveSkinMenu() //Event which gives the menu to the client user interface
{
    Dictionary<string, Dictionary<string, int[]>> obj = new Dictionary<string, Dictionary<string, int[]>>();
    obj["test"] = new Dictionary<string, int[]>(){{ "example", new int[] {1,2,3,4} }}
    SendNuiMessage(JsonConvert.SerializeObject(obj));
}

And finally the manifest:

fx_version 'bodacious'
game 'gta5'

ui_page "index.html"

files {
    "index.html",
    "style.css",
    "script.js",
    "fonts/*.otf",
    "icons/*.svg",
    "Client/bin/Release/**/publish/*.dll",
}

client_script 'Client/bin/Release/**/publish/*.net.dll'
server_script 'Server/bin/Release/**/publish/*.net.dll'

Try this instead:

      <PackageReference Include="Newtonsoft.Json" Version="12.0.3" ExcludeAssets="Compile" GeneratePathProperty="true" />
      <Reference Include="Newtonsoft.Json">
            <HintPath>$(PkgNewtonsoft_Json)\lib\portable-net40+sl5+win8+wp8+wpa81\Newtonsoft.Json.dll</HintPath>
      </Reference>

(it seems v13.x doesn’t include the SL5 PCL assembly anymore)

Nothing new, exact same traceback.
Is it possible that are missing some dipendencies?
These are my imports in ClientMain.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks; // Actually not used
using CitizenFX.Core;
using Newtonsoft.Json;
using static CitizenFX.Core.Native.API;

I have disassembled all my .dll files in my resource (resource.Client.net.dll, Newtonsoft.Json.dll, CitizenFX.Core.Client.dll). This is the beginning (all 3 files looks the same):

Newtonsoft.Json.dll:     file format pei-i386
Newtonsoft.Json.dll
architecture: i386, flags 0x0000012f:
HAS_RELOC, EXEC_P, HAS_LINENO, HAS_DEBUG, HAS_LOCALS, D_PAGED
start address 0x100ac00a

Characteristics 0x2022
	executable
	large address aware
	DLL

Have you found resolution for this issue?
I am running into the same thing.
I have a Newtonsoft.Json.dll that work, but the NuGet Package (latest version) does not work on List or Dictionaries.

Hi,
Unfortunately in my case I found out that many libraries are not usable on the client-side due to the sandboxing, which prevents them to load.
I may be wrong but this is the only conclusion I could come up with.

If you’re developing something big in C#, I’d recommend to write it all in one resource, so that you don’t have to serialize and/or deserialize many things.

I found why the problem and a workaround.
There is a List in my obj, although I did not reference this this in the json data, it fails.
Create a dynamic object with the data I am interested in, it will serialize just fine. Deserialize like this:

T obj = JsonConvert.DeserializeObject<T>(jsonStr);