[CSHARP-1341] Reading Mongo Data Using Web API Created: 30/Jun/15  Updated: 05/Apr/19  Resolved: 07/Feb/17

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.0.1
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Arvind Chary Assignee: Unassigned
Resolution: Done Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows


Attachments: PNG File Web API Mongo error.PNG     PNG File image001.png    

 Description   

I have created a Web API that will read data from Mongo Database and return the collection in the form of List object. Data from Web API is returned without any issues, but when data is accessed from web API in any web forms, it throws following error message: "Duplicate element name ''.".
Please find the attached image for detailed error details.



 Comments   
Comment by Robert Stam [ 05/Apr/16 ]

I think the problem is that Json.NET can't be used to serialize and deserialize BsonDocument values.

If you need to use Json.NET you'll have to use Json.NET's equivalent of BsonDocument (JObject?).

You probably will have to write some conversion routines that convert back and forth between BsonDocument and JObject.

Alternatively, you may find that the .NET driver's built-in JSON support may serve your needs as well.

Comment by Arvind Chary [ 07/Jul/15 ]

Hello Craig,

I am very sorry for delayed response. Below is the List Object as an Image and sample List object which I have converted to JSON, for convenience purpose.

{
  "Distance": 1577.8461993349308,
  "Venues": [
    {
      "NameShort": "Houston Rockets",
      "Address": "1510 Polk St.",
      "City": "Houston",
      "State": "TX",
      "Phone": "7137587460",
      "PhoneFormatted": "713.758.7459",
      "Description": "Houston Rockets",
      "Notables": [
        {
          "NameShort": "None",
          "Id": "5579936d6549f738c0ea5c8b",
          "Name": "None"
        }
      ],
      "Location": {
        "Coordinates": {
          "Values": [
            -95.362272,
            29.750798
          ],
          "Longitude": -95.362272,
          "Latitude": 29.750798
        }
      },
      "Id": "557fe3826549f72330f1f138",
      "Name": "Houston Rockets"
    }
  ],
  "Description": "Specially priced tickets for Houston Rockets and Toyota Center Events.",
  "Instructions": "Code: star",
  "TimeZone": "US/Pacific",
  "Expires": "2015-10-15T13:41:52.625Z",
  "Stats": {
    "Favorites": 12574,
    "UpVotes": 85269,
    "DownVotes": 35707,
    "DetailedViews": 47080,
    "Impressions": 50591
  },
  "Categories": [
    {
      "NamePlural": "Entertainment",
      "NameShort": "Entertainment",
      "Id": "5579936d6549f738c0ea5c03",
      "Name": "Entertainment"
    },
    {
      "NamePlural": "Event Tickets",
      "NameShort": "Event Tickets",
      "Id": "5579936d6549f738c0ea5c3b",
      "Name": "Event Tickets"
    },
    {
      "NamePlural": "Sporting Events",
      "NameShort": "Sporting Events",
      "Id": "5579936d6549f738c0ea5c75",
      "Name": "Sporting Events"
    }
  ],
  "AccessGroups": [
    {
      "NameShort": "UTHealth",
      "Id": "5579936d6549f738c0ea5c02",
      "Name": "University of Texas Health Science Center at Houston"
    }
  ],
  "Suggestions": [
    {
      "Remark": "Products designed for the classroom"
    }
  ],
  "Terms": [
    "Varies with event."
  ],
  "Hours": [
    {
      "Day": 0,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 1,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 2,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 3,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 4,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 5,
      "Open": 930,
      "Close": 2000
    },
    {
      "Day": 6,
      "Open": 930,
      "Close": 2000
    }
  ],
  "Id": "559bd720a19ec942a0b30775",
  "Name": "Specially priced tickets for Houston Rockets and Toyota Centre Events"
}

When I read entire Deals List Object as string it will not throw any error. But when I directly assign it to an List it will throw an error. Below is the code that I have implemented in the Web API:

[Route("api/v1/DealsAPI/GetDeals/{latitude}/{longitude}/{rangeInMeters}/{offset:int=0}/{limit:int=10}/{sortparameter=Distance}/{categoryIds=any}/{accessGroupsIds=any}/{dayNumber=any}")]
 
        //[HttpGet("{latitude}/{longitude}/{rangeInMeters}/{offset:int=0}/{limit:int=10}/{sortparameter:string=Distance}/{categoryIds:string=any}/{accessGroupsIds:string=any}/{dayNumber:string=any}")]
 
        public List<DealResponse> GetDeals(double latitude, double longitude, int offset = 0, int limit = 10, double? rangeInMeters = null, string sortparameter = null,
 
                                                                  string categoryIds = "", string accessGroupsIds = "", string dayNumber = "")
 
        {
 
            List<DealResponse> _dealsList = new List<DealResponse>();
 
            try
 
            {
 
                DealRepository objDeals = new DealRepository(); 
 
                _dealsList = objDeals.searchDealsAsync("deals", latitude, longitude, offset, limit, rangeInMeters, sortparameter, categoryIds, accessGroupsIds, dayNumber).Result;
 
            }
 
            catch (Exception ex)
 
            {
 
            }
 
            return _dealsList;
 
        }

Below is code how I am getting data from API:

protected async void btnGetDeals_Click(object sender, System.EventArgs e)
 
        {
 
            HttpClient client = new HttpClient();
 
            client.BaseAddress = new Uri("http://localhost:5242/");
 
 
 
            // Add an Accept header for JSON format.
 
            client.DefaultRequestHeaders.Accept.Clear();
 
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
 
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
            HttpResponseMessage response = await client.GetAsync("api/v1/DealsAPI/GetDeals/29.764254/-95.367403/90000");
 
           response.EnsureSuccessStatusCode();            try
 
            {
 
                if (response.IsSuccessStatusCode)
 
                {
 
                   var book = response.Content.ReadAsStringAsync().Result;
 
                    var _dealsList = response.Content.ReadAsAsync<List<DealResponse>>().Result; // Here I am getting error as follows: Error converting value "5579936d6549f738c0ea5c8b" to type 'MongoDB.Bson.ObjectId'.   
 
                                                                                                                                                           Path '[0].Venues[0].Notables[0].Id', line 1, position 277.
 
                }
 
                else
 
                {
 
                }
 
            }
 
            catch (Exception ex)
 
            {
 
                throw ex;
 
            }
 
        }

Please help me in fixing this issue.

Thanks,

Arvind

Comment by Craig Wilson [ 03/Jul/15 ]

We need more information than this... It appears you are using JSON.NET and it's likely there is a mismatch between translation between our BsonDocument and their JSON serializers. Perhaps you could provide some code?

Generated at Wed Feb 07 21:39:19 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.