-2

源/目标类型

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 上推送了一个问题,但我仍然在那里问,因为我太紧张了,无法等待......

4

2 回答 2

2

您提供的 JSON 似乎无效。键必须用引号括起来。尝试这个: { "FirstText": 1, "SecondText": 2 }

编辑:如果您打算在源中对 JSON 进行硬编码,请确保对其进行转义,以便正确解释它。

于 2019-01-04T15:24:00.730 回答
0

Sandboxed AppDomain 需要对引用的完全信任,它可以通过两种方式给出: 1. 在 GAC 中注册的程序集。2. 使用 AppDomain.CreateDomain 时设置程序集为 fullTrustAssemblies 和 StrongName。

于 2019-01-05T12:51:18.347 回答