Reputation: 139
I have Powershell 3.0 with .Net framework 4.0 on Windows 7 x64. When I try to use a type from C# file that uses System.Runtime.Serialization.Json.DataContractJsonSerializer I constanly get
"Add-Type : t:\Powershell_Json_Test.cs(13) : The type or namespace name 'Json' does not exist in the namespace 'System.Runtime.Serialization' (a missing an assembly reference?)"
The error appears on line
Add-Type -Path "$($MyPath)\Powershell_Json_Test.cs"
of Powershell_Json_Test.ps1. At the same time the $srs contains object System.Runtime.Serialization.Json.DataContractJsonSerializer (as well as 400+ other objects). i.e. System.Runtime.Serialization.dll contains System.Runtime.Serialization.Json.DataContractJsonSerializer and it should be available for usage.
Does anyone have idea why the error appears?
When I try to use Powershell_Json_Test.cs from c# code all works as expected.
Powershell_Json_Test.ps1
$MyPath = $(Split-Path -Path $MyInvocation.MyCommand.Path)
$srs = Add-Type -Assembly System.Runtime.Serialization -PassThru
Add-Type -Path "$($MyPath)\Powershell_Json_Test.cs"
$Hlpr = New-Object -TypeName "Test.Json.Helper"
$Obj = $Hlpr.GetInfo('{"Date":"2019-01-01","Result":2}')
Powershell_Json_Test.cs
using System;
using System.Text;
using System.IO;
namespace Test.Json
{
public class Info
{
public string Date { get; set; }
public int Result { get; set; }
}
public class Helper
{
public static string Serialize<T>(T obj)
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
public Info GetInfo(string JSON) {
return Deserialize<Info>(JSON);
}
}
}
Upvotes: 1
Views: 735
Reputation: 139
Just found how to avoid the error. I had to use
Add-Type -Path "$($MyPath)\Powershell_Json_Test.cs" -ReferencedAssemblies System.Xml,System.Runtime.Serialization
instead of
Add-Type -Path "$($MyPath)\Powershell_Json_Test.cs"
Upvotes: 3