范围:
我正在写一个 set of tools帮助人们在他们的 MongoDB 数据库上运行常见操作,“导出”数据就是其中之一。
目前我支持完整的 JSON 导出和“CSV”,但后者更棘手。
导出工具允许使用“ConfigFile”指定哪些字段将被反序列化(来自 BsonDocument ),而不关心它们的类型。目前大多数类型都可以使用,但“ISO”日期仍然让我头疼。
动态反序列化
目前我依赖JObjects处理“Json”文档的解析,就像这样:
// Json Writer Settings - To avoid problems with 10Gen types
var jsonSettings = new JsonWriterSettings () { OutputMode = JsonOutputMode.Strict };
// Mapping string to a dynamic json object
JObject mappedJson = JObject.Parse (jsonObject.ToJson (jsonSettings));
// Trying to extract property values out of the object
foreach (Field field in _configuration.Fields)
{
// Checking for JToken Type
JTokenType objType = fieldData.Type;
// Sanity Check for NULL Values of properties that do exist
if (objType == JTokenType.Null)
{
fieldValue = String.Empty;
}
else if (objType == JTokenType.Array) // Checking for Arrays (that need to be serialized differently)
{
String[] valuesArray = fieldData.Select (t => t.Value<String> ().Replace (_configuration.ListDelimiter, String.Empty)
.Replace (_configuration.Delimiter, String.Empty)).ToArray ();
fieldValue = String.Join (_configuration.ListDelimiter, valuesArray);
}
else if (objType == JTokenType.Object && field.Name.Equals ("_id")) // Checking for specific MongoDB "_id" situation
{
fieldValue = fieldData.ToObject<String> (); // Value<ObjectId> ().ToString ();
}
else
{
// Reaching Attribute Value as "String" (if nothing else worked)
fieldValue = fieldData.Value<String> ();
}
}
问题:
此代码适用于我目前测试过的所有类型,但“DateTime”除外。 MongoDB 存储的方式如下:"PublicationDate": ISODate("2014-08-10T00:00:00.000Z"),这完全打破了我的反序列化。
我曾尝试将其反序列化为“DateTime”和“Object”,但它们都无法正常工作。有什么正确的方法可以做到这一点吗?这基本上是我使这个“动态导出器”工作所缺少的全部。
提前致谢
最佳答案
try catch 可能是捕获 iso datetime 的糟糕方法的解决方案?像 JTokenType.Date。
using System.Globalization;
public static void ParseMongoDBISODate()
{
// Json Writer Settings - To avoid problems with 10Gen types
var jsonSettings = new JsonWriterSettings() { OutputMode = JsonOutputMode.Strict };
// Mapping string to a dynamic json object
JObject mappedJson = JObject.Parse(jsonObject.ToJson(jsonSettings));
// Trying to extract property values out of the object
foreach (Field field in _configuration.Fields)
{
// Checking for JToken Type
JTokenType objType = fieldData.Type;
// Sanity Check for NULL Values of properties that do exist
if (objType == JTokenType.Null)
{
fieldValue = String.Empty;
}
// Checking for Arrays (that need to be serialized differently)
else if (objType == JTokenType.Array)
{
String[] valuesArray = fieldData.Select(t => t.Value<String>().Replace(_configuration.ListDelimiter, String.Empty).Replace(_configuration.Delimiter, String.Empty)).ToArray();
fieldValue = String.Join(_configuration.ListDelimiter, valuesArray);
}
// Checking for specific MongoDB "_id" situation
else if (objType == JTokenType.Object && field.Name.Equals("_id"))
{
fieldValue = fieldData.ToObject<String>(); // Value<ObjectId> ().ToString ();
}
else
{
try // it's a bad way but you can set fieldValue as a DateTime
{
//JTokenType.Date
DateTime mongoDBISODate = DateTime.Parse(fieldData.Value<String>(), null, DateTimeStyles.RoundtripKind);
fieldValue = mongoDBISODate;
}
catch (Exception)
{
// Reaching Attribute Value as "String" (if nothing else worked)
fieldValue = fieldData.Value<String>();
}
}
}
}
关于c# - 是否可以将 MongoDB 的 "ISODate"字段反序列化为 JToken (C#)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630816/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test