源/目标类型
public struct MyStruct
{
public int FirstText { get; set; }
public int SecondText { get; set; }
}
源/目标 JSON
{FirstText:1,SecondText:2}
预期行为
当我在单个 exe 演示中使用它时: 1 - 2
实际行为
当我在 C# 类库中使用它时,它崩溃了:
System.Reflection.TargetInvocationException: Exception has been thrown by the ta
rget of an invocation. ---> System.Security.SecurityException: Request failed.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOn
ly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Bo
olean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipChec
kThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean s
kipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory.<>c__DisplayC
lass9`1.<CreateDefaultConstructor>b__7()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject
(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMem
ber, JsonProperty containerProperty, String id, Boolean& createdFromNonDefaultCr
eator)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(Js
onReader reader, Type objectType, JsonContract contract, JsonProperty member, Js
onContainerContract containerContract, JsonProperty containerMember, Object exis
tingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInte
rnal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty mem
ber, JsonContainerContract containerContract, JsonProperty containerMember, Obje
ct existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Jso
nReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type
objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, Jso
nSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSeriali
zerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
重现步骤
var test = Newtonsoft.Json.JsonConvert.DeserializeObject<MyStruct>("{FirstText:1,SecondText:2}");
System.Console.WriteLine("{0} - {1}", test.FirstText, test.SecondText);
当我在单个exe演示中使用 Json.NET 时,它可以正常工作。但是当我在 C# 类库中使用它时,它不起作用。我在 github 上推送了一个问题,但我仍然在那里问,因为我太紧张了,无法等待......
您提供的 JSON 似乎无效。密钥必须用引号括起来。试试这个: { "FirstText": 1, "SecondText": 2 }
编辑:如果您打算在源中对JSON进行硬编码,请确保对其进行转义,以便可以正确解释它。
沙盒 AppDomain 需要对引用进行完全信任,可以通过两种方式提供: 1. 在 GAC 注册大会。 2. 使用 AppDomain.CreateDomain 时,将程序集设置为具有强名称的 fullTrustAssemblies。