Home > database >  JSON reader was expecting a value but found 'string' .NET
JSON reader was expecting a value but found 'string' .NET

Time:11-12

I'm running a select in mongoDb with the following code:

var projects = GenerateProject(customizations);
            var result = _mongoDbRepository
                    .SetDatabase("mydatabase")
                    .GetCollection(myCollection)
                    .Aggregate()
                    .Match(myFilter)
                    .Project<dynamic>(projects)
                    .ToList();

GenerateProject Class:

 private static string GenerateProject(List<MyClass> customizations)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("{ '_id':0");

        foreach (var item in customizations)
        {
            sb.Append(", '");
            sb.Append(item.Name);
            sb.Append("':1");
        }

        sb.Append(" }");
        return sb.ToString();
    }

but on return I get the error:

JSON reader was expecting a value but found 'string'

Can anyone tell me what could be going on?

CodePudding user response:

I try your code.

The problem is on your match stage. You should check what is inside your myFilter.

Works fine.

var customizations = new List<MyClass>() { new MyClass() { Name = "123", _id = "456" } };
var projects = GenerateProject(customizations);
var result = database.GetCollection<BsonDocument>("month")
      .Aggregate()
      .Match("{}")
      .Project<dynamic>(projects)
      .ToList();

Not work.

var customizations = new List<MyClass>() { new MyClass() { Name = "123", _id = "456" } };
var projects = GenerateProject(customizations);
var result = database.GetCollection<BsonDocument>("month")
      .Aggregate()
      .Match("")
      .Project<dynamic>(projects)
      .ToList();

CodePudding user response:

Not completely sure if it's problem (but given the error, it's possible) but it looks like you're trying to manually create some JSON in the GenerateProject method manually.

Never, ever, ever attempt to generate JSON "by hand" like this, especially when there are dedicated tools to do this.

Add all of your entries to a Dictionary<string, int> and pass that to the serialiser to generate correct JSON.

private static string GenerateProject(List<MyClass> customizations)
{
    var dict = new Dictionary<string, int>();
    dict.Add("_id", 0);

    foreach (var item in customizations)
    {
        dict.Add(item.Name, 1);
    }

    return JsonSerializer.Serialize(dict);
}

var json = GenerateProject(new List<MyClass>{
   new MyClass{ Name = "one" },
   new MyClass{ Name = "two" },
   new MyClass{ Name = "three" },
});
// gives {"_id":0,"one":1,"two":1,"three":1}
  • Related