C# 将文档从 mongodb 读取到 JSON 中并尝试获取值

标签 c# json mongodb parsing

<分区>

我是 JSON 的新手,所以这可能是一个简单的问题。我有下面的代码(下面还有一个 json 对象)。

我只想能够读取 JSON 并将其中的项目放入变量中以使其可读。

我收到错误,这是由于返回 JSON 对象中的文本 ObjectID(""): 解析值时遇到意外字符:O.路径“_id”,第 1 行,位置 10。

从 MONGO 返回的 JSON 对象:

{
    "_id": ObjectId("543c2d426b6b5ef78b62fc41"),
    "LoanStatusAddedEvent": {
        "@From": "Lakewood",
        "@MessageTimeDateStamp": "2013-08-12T05:03:23.035-04:00",
        "@MessageID": "29055040",
        "LoanNumber": "5300494930",
        "CurrentIndicator": "true",
        "StatusChangeDate": "2013-08-11T20:01:01.000",
        "StatusValue": "42",
        "StatusType": "Active"
    }
}

代码:

        // connect to the mongo server and the Mongos DB
        string connectionString = "connectionstringhere";


        MongoServer mongo = MongoServer.Create(connectionString);
        mongo.Connect();

        MongoDatabase database = mongo.GetDatabase("Mangos");


        //Builds new Collection (looking at JsonImports on server)
        MongoCollection<LoanStatus> collection2 = database.GetCollection<LoanStatus>("JsonImports");


        var collection = database.GetCollection<BsonDocument>("JsonImports");


        var query = new QueryDocument(); //("LoanNumber", "5300494930");


        foreach (BsonDocument item in collection.Find(query))
        {
            string json = item.ToJson();

            Console.WriteLine(item);


            // code here to below http://james.newtonking.com/json/help/index.html?topic=html/QueryingLINQtoJSON.htm
            JObject rss = JObject.Parse(json);

            string rssLoanNumber = (string)rss["LoanStatusAddedEvent"]["LoanNumber"];

            Console.WriteLine(rssLoanNumber);



        }// end for each loop


        Console.WriteLine();
        Console.Read();


public class LoanStatus
{
    public string From { get; set; }

    public string MessageTimeDateStamp { get; set; }

    public string MessageID { get; set; }

    public string LoanNumber { get; set; }

    public string CurrentIndicator { get; set; }

    public string StatusChangeDate { get; set; }

    public string StatusValue { get; set; }

    public string StatusType { get; set; }

    //public string id { get; set; }



    public void PrintDetailsToScreen()
    {
        Console.WriteLine(String.Format("{0}{1}{2}",
                            this.LoanNumber, this.StatusChangeDate, this.StatusValue));
    }

}

public class RootObject
{
    public LoanStatus LoanStatus { get; set; }
}

最佳答案

您的对象应该有一个 FieldProperty,名称为 _idId 类型为 ObjectId.

public ObjectId Id { get; set; }

如果您可以重建您的 mongo 数据库,您可以将 Id 的类型更改为 String 而不是 ObjectId 并通过

告诉 mongo 驱动程序将所有 id 视为字符串
BsonSerializer.RegisterIdGenerator(typeof(string), new StringObjectIdGenerator());

如果这样做,您可以使用任何 string 作为 Id,如果它为空,MongoDb 会为您的文档创建一个随机的 Id

  • 更新:

Mongodb 文档不是有效的 Json 文档。它有一些不会用 json.net 解析的值。 您应该手动删除它们。有一个简单的代码

var json = "ObjectId(\"123\")";
var result =  Regex.Match(json, @"ObjectId\(([^\)]*)\)").Value;
var id = result.Replace("ObjectId(", string.Empty).Replace(")", String.Empty);
var validJson = json.Replace(result, id);

关于C# 将文档从 mongodb 读取到 JSON 中并尝试获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26389293/

相关文章:

json - 使用 Spring Boot 和 Hibernate 的 Jackson - 使用 @JsonIdentityInfo 从 Id 创建对象

javascript - 转换 JSON 对象中的 promise

javascript - PUT 方法出错。 AngularJS、NodeJS

python - 将 PySpark 数据帧写入 MongoDB 插入字段作为 ObjectId

c# - 搜索列表并按最大找到的值排序列表 c#

c# - ReflectionTypeLoadException 在程序包管理器控制台中运行添加迁移命令时出错

c# - 奇怪的动态类型参数问题

javascript - 如何使用 ng-repeat 显示带有条件的 json 数组?

node.js - 我需要为 MongoDB 启用身份验证吗?

c# - 从 MembershipUser 继承 - Asp.net/C#