c# - 类型为 'Newtonsoft.Json.Linq.JObject' 的对象无法转换为类型

标签 c# json xna json.net

我正在使用 JSON.NET 通过反射将一些数据解析为一些特定的属性。

property.SetValue(comInstance, field.Value);

这一行抛出一个ArgumentException:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Object of type 'Newtonsoft.Json.Linq.JObject' cannot be converted to type 'Microsoft.Xna.Framework.Vector2'.

我知道这一定与我的 JsonConverter for Vector2 类型有关,它看起来像这样:

public class Vector2Converter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Vector2));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonObject = JObject.Load(reader);
        var properties = jsonObject.Properties().ToList();
        return new Vector2
        {
            X = (float)properties[0].Value,
            Y = (float)properties[1].Value
        };
    }
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Vector2 v = (Vector2)value;
        writer.WriteStartObject();
        writer.WritePropertyName("X");
        serializer.Serialize(writer, v.X);
        writer.WritePropertyName("Y");
        serializer.Serialize(writer, v.Y);
        writer.WriteEndObject();
        
    }
}

现在,我注意到 write 被调用了,但是 read 从来没有调用过。 我这样反序列化:

JsonConvert.DeserializeObject<EntityJson>(json, JsonUtility.Settings);

JsonUility.Settings 包含 Vector2Converter

然后我这样序列化:

JsonConvert.SerializeObject(entityJson, Formatting.Indented, JsonUtility.Settings);

JSON 中的字段本身看起来也不错:

"Center": {
      "X": 116.0,
      "Y": 65.0
    },

谁能帮帮我?

编辑:

internal class EntityJson
{
    public string Name { get; set; }
    public Dictionary<string, ComponentJson> Components { get; set; }
    
    public EntityJson()
    {
        Components = new Dictionary<string, ComponentJson>();
    }

    public Entity ToEntity()
    {
        Entity entity = new Entity(Name);

        foreach(KeyValuePair<string, ComponentJson> com in Components)
        {
            ObjectHandle handle = Activator.CreateInstance(com.Value.Namespace, com.Value.Namespace +"."+ com.Key);
            Object handleValue = handle.Unwrap();
            Component comInstance = (Component)handleValue;

            foreach(KeyValuePair<string, object> field in com.Value.Fields)
            {
                PropertyInfo property = comInstance.GetType().GetProperty(field.Key, 
                    BindingFlags.NonPublic | 
                    BindingFlags.Public | 
                    BindingFlags.Instance);

                property.SetValue(comInstance, field.Value); // <-- field.Value
            }

            entity.AddUnsafe(comInstance);
        }

        return entity;
    }
}

field.value 将是一个 JObject 而不是 Vector2,异常状态:

it cannot be casted.

最佳答案

好的,我通过这样做设法解决了这个问题:

object result = field.Value;
if (field.Value.GetType() == typeof(JObject))
{
      JToken token = (JToken)field.Value;
      result = token.ToObject(property.PropertyType, JsonSerializer.Create(JsonUtility.Settings));
}
else
{
      result = Convert.ChangeType(result, property.PropertyType);
}

property.SetValue(comInstance, result); 

这是一个稳定的解决方案吗?

关于c# - 类型为 'Newtonsoft.Json.Linq.JObject' 的对象无法转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399754/

相关文章:

c# - 检查身份验证票过期而不影响它

json - 在javascript中导入json似乎没有成功

ios - 无法在 HOME.VC 文本标签中显示 JSON 结果

javascript - 使用 d3.js 和给定的 json 文件结构进行捆绑布局

c# - 如果我尝试播放mp3文件,我的代码会崩溃,对于WAV文件效果很好

c# - 如何使用 C# 从 JSON 字符串中删除特定属性

c# - 如何将PCM数据转换为wav文件?

c# - 不使用ORM的N层数据库应用程序,UI如何指定需要显示的数据?

c# - 在 C# 中使用 BinaryReader 编写 Java ObjectOutputStream.writeInt() 读取?

c# - C# XNA 与 Farseer Physics 中的 OnCollision 事件处理程序问题