1

I am working on a server and a client, the server is written in C++ and the client is written in C#.

On the client side I am using Newtonsoft's "Json.net" and also the bson from Newtonsoft.

I am trying to send a bson that one of its' keys has multiple values (or a list value) that look something like this:

{
"price": "193"
"cart": ["apple", "banana", "watermelon"]
 }

I made a class that I can deserialize the bson into which looks like this:

public class Order
{
    public int price {get; set;}
    public string[] cart {get; set;}
}

and the deserialization looks like this:


    byte[] data; // let's say our bson is in this array
    // {
    // "price": "193"
    // "cart": ["apple", "banana", watermelon"]
    //}

    
    MemoryStream ms = new MemoryStream(data);
    using (BsonReader reader = new BsonReader(ms))
    {
        JsonSerializer serializer = new JsonSerializer();
    
        Order o = serializer.Deserialize<Order>(reader);
    }
    
    Console.WriteLine(o.cart); // error: cart is null

I took this deserialization code straight from the documentation here.

No matter what I tried, the cart property always returns as null. I tried replacing the string array with a List<string> but still no luck.

Am I missing something?

edit:

problem solved. I replaced the BsonReader to BsonDataReader and that sloved the problem.

eladGN
  • 13
  • 3
  • Do you have some sample BSON binary data you could share, maybe as a Base64 encoded string? – dbc Jun 13 '22 at 18:42
  • I don't know if this is your problem, but [`BsonReader`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Bson_BsonReader.htm) is obsolete. Use [`BsonDataReader`](https://github.com/JamesNK/Newtonsoft.Json.Bson/blob/master/Src/Newtonsoft.Json.Bson/BsonDataReader.cs) from Newtonsoft.Json.Bson as explained in [How to convert JSON to BSON using Json.NET](https://stackoverflow.com/a/45029475). – dbc Jun 13 '22 at 18:48
  • If I use `BsonDataWriter` and `BsonDataReader` from [Newtonsoft.Json.Bson](https://www.nuget.org/packages/Newtonsoft.Json.Bson/) then your `Order` model round-trips successfully, see https://dotnetfiddle.net/bNAp4K. Can you please share a [mcve] - or confirm that simply upgrading to `BsonDataReader` solves the problem? ... actually the old `BsonReader` seems to work OK despite being obsolete, see https://dotnetfiddle.net/jlLfPC. To help you, I think we need to see a [mcve] with some sample BSON that cannot be deserialized. See [ask]. – dbc Jun 13 '22 at 18:52
  • 2
    Thank you so much! It works! I needed to change the ```BsonReader``` to ```BsonDataReader``` and that solved the problem! – eladGN Jun 13 '22 at 19:03

0 Answers0