简体   繁体   English

序列化包含数组的文档

[英]Serialize a document that contains arrays

I'm using MongoDB and C# to record the coordinates of my game players. 我正在使用MongoDB和C#记录游戏玩家的坐标。 My collection contains documents that follow the following structure: 我的收藏集中包含遵循以下结构的文档:

{
    "_id" : ObjectId("5d12bc34c45f0a1a685db405"),
    "Coordinates" : [ 
        {
            "x" : -5.75,
            "y" : -0.47392401099205
        }, 
        {
            "x" : -5.75,
            "y" : -0.481772005558014
        }],
        "Player" : "Player 1"
}

But I'm having some issues serializing this information, I tried something like that: 但是我在序列化此信息时遇到一些问题,我尝试过类似的方法:

public class Scores  {

 [MongoDB.Bson.Serialization.Attributes.BsonElement]
 public ObjectId _id { get; set; }
 public Object[] Coordinates { get; set; }
 public float x  { get; set; }
 public float y  { get; set; }
 public string Player { get; set; }
}
...
foreach (var document in scoreCollection.Find(new QueryDocument("Player", "Player1"))){
    Debug.Log ("Get one info: \n" + document);
}

But I keep receiving this error: 但我一直收到此错误:

Element 'x' does not match any field or property of class UnityEngine.Object. 元素“ x”与UnityEngine.Object类的任何字段或属性都不匹配。 MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize

How can I fix my code? 如何修复我的代码?

Create am additional model to store the coordinates 创建其他模型以存储坐标

public class Coordinate {
    public float x  { get; set; }
    public float y  { get; set; }
}

And update the model with an array of them 并用它们的数组更新模型

public class Scores  {
     [MongoDB.Bson.Serialization.Attributes.BsonElement]
     public ObjectId _id { get; set; }
     public Coordinate[] Coordinates { get; set; }
     public string Player { get; set; }
}

This should now match the given JSON structure. 现在,这应该与给定的JSON结构匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM