MongoDB C# Model from JSON
时间: 2023-11-27 19:06:07 浏览: 122
To generate a C# model from a JSON schema in MongoDB, you can use the built-in BSON serializer and deserializer provided by the MongoDB driver for .NET.
First, create a new C# class with properties matching the fields in your JSON schema. For example, if your JSON schema looks like this:
```json
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
```
Create a C# class like this:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
```
Then, you can use the MongoDB driver's BSON serializer and deserializer to serialize and deserialize your JSON data to and from your C# model.
For example, to deserialize a JSON document into a C# object:
```csharp
string json = "{ \"name\": \"John Doe\", \"age\": 30, \"address\": { \"street\": \"123 Main St\", \"city\": \"Anytown\", \"state\": \"CA\", \"zip\": \"12345\" } }";
var person = BsonSerializer.Deserialize<Person>(json);
```
And to serialize a C# object to JSON:
```csharp
var person = new Person { Name = "John Doe", Age = 30, Address = new Address { Street = "123 Main St", City = "Anytown", State = "CA", Zip = "12345" } };
string json = person.ToJson();
```
阅读全文