首页 > c# > Unity中的Json.net用于序列化

Unity中的Json.net用于序列化 (Json.net in Unity for serialization)

问题

我一直在为我的Unity项目寻找一个更好的json库。我需要使用除属性名称以外的其他名称进行序列化,反序列化包含任意用户定义内容的字典,并忽略序列化中的空字段。我已将Json.NET v12.0.1的.dll(net20)添加到我的Unity项目中,它似乎在我的(有限)测试中正常工作。

public class Foo
{
    [JsonProperty("baz", NullValueHandling = NullValueHandling.Ignore)]
    public Bar Baz{ get; set; }

    [JsonProperty("quux", NullValueHandling = NullValueHandling.Ignore)]
    public Qux Quux{ get; set; }
}

public class Corge: Dictionary<string, JObject>
{
    //whatever the user wants to send will come back from the REST call
}

public void OnResponse(string responseJson)
{
    var corge = JsonConvert.DeserializeObject<Corge>(responseJson);
    var name = corge["name"].ToString();
}

在我完全重构我的项目之前,在Unity中使用Json.NET并发布到不同平台会有任何限制吗?使用dynamic工作比扩展更好Dictionary吗?

解决方法

作为这个问题的后续内容,在实现Json.NET库之后,在iOS平台上发出REST请求存在问题。

Exception: System.NotSupportedException: System.Reflection.Emit.DynamicMethod::.ctor
at System.Reflection.Emit.DynamicMethod..ctor (System.String name, System.Type returnType, System.Type[] parameterTypes, System.Type owner, System.Boolean skipVisibility)

我们最终切换到Json.NET for Unity,这似乎工作得很好。

问题

I've been looking for a better json library for my Unity project. I need to be serialize using a different name other than the property name, deserialize dictionaries containing arbitrary user defined content and ignore null fields in serialization. I've added the .dll (net20) for Json.NET v12.0.1 to my Unity project and it seems to work fine in my (limited) testing.

public class Foo
{
    [JsonProperty("baz", NullValueHandling = NullValueHandling.Ignore)]
    public Bar Baz{ get; set; }

    [JsonProperty("quux", NullValueHandling = NullValueHandling.Ignore)]
    public Qux Quux{ get; set; }
}

public class Corge: Dictionary<string, JObject>
{
    //whatever the user wants to send will come back from the REST call
}

public void OnResponse(string responseJson)
{
    var corge = JsonConvert.DeserializeObject<Corge>(responseJson);
    var name = corge["name"].ToString();
}

Before I completely refactor my project will there be any limitations using Json.NET in Unity and publishing to different platforms? Would using dynamic work better than extending Dictionary?

解决方法

As a follow up to this question, after implementing the Json.NET library there were issues making REST requests on the iOS platform.

Exception: System.NotSupportedException: System.Reflection.Emit.DynamicMethod::.ctor
at System.Reflection.Emit.DynamicMethod..ctor (System.String name, System.Type returnType, System.Type[] parameterTypes, System.Type owner, System.Boolean skipVisibility)

We ended up switching to Json.NET for Unity which seems to be working fine.

相似信息