我是JSON的新手,所以这可能是一个简单的问题。我有下面的代码(带有json对象,再次在下面)。
我只是希望能够读取JSON并将其中的项目放入变量中以便于读取。
我收到错误,这是由于返回的JSON对象中的文本ObjectID("")
:
Unexpected character encountered while parsing value: O. Path '_id', line 1, position 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; }
}
答案 0 :(得分:2)
您的对象应该有Field
或Property
,其名称为_id
或Id
,类型为ObjectId
。
public ObjectId Id { get; set; }
如果您可以重新构建您的mongo数据库,则可以将Id
的类型更改为String
而不是ObjectId
并告诉mongo驱动程序将所有id视为字符串
BsonSerializer.RegisterIdGenerator(typeof(string), new StringObjectIdGenerator());
如果你这样做,你可以使用任何string
作为Id
,如果它为空,MongoDb会为你的文档创建一个随机Id
Mongodb Docuemnt不是有效的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);