简体   繁体   中英

Serialize a document that contains arrays

I'm using MongoDB and C# to record the coordinates of my game players. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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