- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 mongo 中有这样的数据:
"trd" : ISODate("2003-12-08T00:00:00Z")
现在,我正在像这样从 Mongo 获取数据作为 BsonDocument:
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("wsid", id);
var mongoListBatch = _client.GetManyByFilter(filter, "directory");
JsonWriterSettings settings = new JsonWriterSettings();
settings.OutputMode = JsonOutputMode.Strict;
var lists = mongoListBatch.ToJson(settings);
问题是我希望在 json 中得到像这样的 DateTime 对象:
"transactiedatum": "23-02-1993"
但是,我得到:
"transactiedatum": {
"$date": 1070841600000
}
首先,它的unix时间格式,其次,json结构有变化。我该如何处理?
最佳答案
我们遇到了类似的问题。这听起来很复杂,但没什么大不了的。
所以,首先,这是 github 上 Mongo C# 驱动器的链接: MongoC#Driver
对你来说,这里有两个重要的链接:
我们想要实现的是我们不希望 Json 字符串中的表示是 unix 时间戳格式,所以我们将这些类以不同的名称复制到我们的项目中,所以,这里是所有的类:
扩展类:
using System;
using System.IO;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson;
namespace Fishing.MongoDB.Serializers
{
public static class MyJsonWriterSettings
{
/// <summary>
/// Serializes an object to a BSON byte array.
/// </summary>
/// <typeparam name="TNominalType">The nominal type of the object.</typeparam>
/// <param name="obj">The object.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="writerSettings">The writer settings.</param>
/// <param name="configurator">The serialization context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>A BSON byte array.</returns>
public static byte[] ToBson<TNominalType>(
this TNominalType obj,
IBsonSerializer<TNominalType> serializer = null,
BsonBinaryWriterSettings writerSettings = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs)
)
{
return ToBson(obj, typeof(TNominalType), writerSettings, serializer, configurator, args);
}
/// <summary>
/// Serializes an object to a BSON byte array.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="nominalType">The nominal type of the object..</param>
/// <param name="writerSettings">The writer settings.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="configurator">The serialization context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>A BSON byte array.</returns>
/// <exception cref="System.ArgumentNullException">nominalType</exception>
/// <exception cref="System.ArgumentException">serializer</exception>
public static byte[] ToBson(
this object obj,
Type nominalType,
BsonBinaryWriterSettings writerSettings = null,
IBsonSerializer serializer = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs))
{
if (nominalType == null)
{
throw new ArgumentNullException("nominalType");
}
if (serializer == null)
{
serializer = BsonSerializer.LookupSerializer(nominalType);
}
if (serializer.ValueType != nominalType)
{
var message = string.Format("Serializer type {0} value type does not match document types {1}.", serializer.GetType().FullName, nominalType.FullName);
throw new ArgumentException(message, "serializer");
}
using (var memoryStream = new MemoryStream())
{
using (var bsonWriter = new BsonBinaryWriter(memoryStream, writerSettings ?? BsonBinaryWriterSettings.Defaults))
{
var context = BsonSerializationContext.CreateRoot(bsonWriter, configurator);
args.NominalType = nominalType;
serializer.Serialize(context, args, obj);
}
return memoryStream.ToArray();
}
}
/// <summary>
/// Serializes an object to a BsonDocument.
/// </summary>
/// <typeparam name="TNominalType">The nominal type of the object.</typeparam>
/// <param name="obj">The object.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="configurator">The serialization context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>A BsonDocument.</returns>
public static BsonDocument ToBsonDocument<TNominalType>(
this TNominalType obj,
IBsonSerializer<TNominalType> serializer = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs))
{
return ToBsonDocument(obj, typeof(TNominalType), serializer, configurator, args);
}
/// <summary>
/// Serializes an object to a BsonDocument.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="nominalType">The nominal type of the object.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="configurator">The serialization context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>A BsonDocument.</returns>
/// <exception cref="System.ArgumentNullException">nominalType</exception>
/// <exception cref="System.ArgumentException">serializer</exception>
public static BsonDocument ToBsonDocument(
this object obj,
Type nominalType,
IBsonSerializer serializer = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs))
{
if (nominalType == null)
{
throw new ArgumentNullException("nominalType");
}
if (obj == null)
{
return null;
}
if (serializer == null)
{
var bsonDocument = obj as BsonDocument;
if (bsonDocument != null)
{
return bsonDocument; // it's already a BsonDocument
}
var convertibleToBsonDocument = obj as IConvertibleToBsonDocument;
if (convertibleToBsonDocument != null)
{
return convertibleToBsonDocument.ToBsonDocument(); // use the provided ToBsonDocument method
}
serializer = BsonSerializer.LookupSerializer(nominalType);
}
if (serializer.ValueType != nominalType)
{
var message = string.Format("Serializer type {0} value type does not match document types {1}.", serializer.GetType().FullName, nominalType.FullName);
throw new ArgumentException(message, "serializer");
}
// otherwise serialize into a new BsonDocument
var document = new BsonDocument();
using (var bsonWriter = new BsonDocumentWriter(document))
{
var context = BsonSerializationContext.CreateRoot(bsonWriter, configurator);
args.NominalType = nominalType;
serializer.Serialize(context, args, obj);
}
return document;
}
/// <summary>
/// Serializes an object to a JSON string.
/// </summary>
/// <typeparam name="TNominalType">The nominal type of the object.</typeparam>
/// <param name="obj">The object.</param>
/// <param name="writerSettings">The JsonWriter settings.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="configurator">The serializastion context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>
/// A JSON string.
/// </returns>
public static string ToMyJson<TNominalType>(
this TNominalType obj,
JsonWriterSettings writerSettings = null,
IBsonSerializer<TNominalType> serializer = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs))
{
return ToMyJson(obj, typeof(TNominalType), writerSettings, serializer, configurator, args);
}
/// <summary>
/// Serializes an object to a JSON string.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="nominalType">The nominal type of the objectt.</param>
/// <param name="writerSettings">The JsonWriter settings.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="configurator">The serialization context configurator.</param>
/// <param name="args">The serialization args.</param>
/// <returns>
/// A JSON string.
/// </returns>
/// <exception cref="System.ArgumentNullException">nominalType</exception>
/// <exception cref="System.ArgumentException">serializer</exception>
public static string ToMyJson(
this object obj,
Type nominalType,
JsonWriterSettings writerSettings = null,
IBsonSerializer serializer = null,
Action<BsonSerializationContext.Builder> configurator = null,
BsonSerializationArgs args = default(BsonSerializationArgs))
{
if (nominalType == null)
{
throw new ArgumentNullException("nominalType");
}
if (serializer == null)
{
serializer = BsonSerializer.LookupSerializer(nominalType);
}
if (serializer.ValueType != nominalType)
{
var message = string.Format("Serializer type {0} value type does not match document types {1}.", serializer.GetType().FullName, nominalType.FullName);
throw new ArgumentException(message, "serializer");
}
using (var stringWriter = new StringWriter())
{
using (var bsonWriter = new JsonWriterMine(stringWriter, writerSettings ?? JsonWriterSettings.Defaults))
{
var context = BsonSerializationContext.CreateRoot(bsonWriter, configurator);
args.NominalType = nominalType;
serializer.Serialize(context, args, obj);
}
return stringWriter.ToString();
}
}
}
}
所以基本上,将整个类从 github 复制到您自己的类中,并将 2 个方法的名称:ToJson() 更改为您的方法之一。在这里你可以看到我的是 ToJsonMine()。
现在,到第二节课你需要:
JsonWriter
using MongoDB.Bson.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MongoDB.Bson;
namespace Fishing.MongoDB.Serializers
{
public class JsonWriterMine : BsonWriter
{
// private fields
private TextWriter _textWriter;
private JsonWriterSettings _jsonWriterSettings; // same value as in base class just declared as derived class
private InternalJsonWriterContext _context;
// constructors
/// <summary>
/// Initializes a new instance of the JsonWriter class.
/// </summary>
/// <param name="writer">A TextWriter.</param>
public JsonWriterMine(TextWriter writer)
: this(writer, JsonWriterSettings.Defaults)
{
}
/// <summary>
/// Initializes a new instance of the JsonWriter class.
/// </summary>
/// <param name="writer">A TextWriter.</param>
/// <param name="settings">Optional JsonWriter settings.</param>
public JsonWriterMine(TextWriter writer, JsonWriterSettings settings)
: base(settings)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
_textWriter = writer;
_jsonWriterSettings = settings; // already frozen by base class
_context = new InternalJsonWriterContext(null, ContextType.TopLevel, "");
State = BsonWriterState.Initial;
}
/// <summary>
/// Writes a BSON DateTime to the writer.
/// </summary>
/// <param name="value">The number of milliseconds since the Unix epoch.</param>
public override void WriteDateTime(long value)
{
if (Disposed) { throw new ObjectDisposedException("JsonWriter"); }
if (State != BsonWriterState.Value && State != BsonWriterState.Initial)
{
ThrowInvalidState("WriteDateTime", BsonWriterState.Value, BsonWriterState.Initial);
}
WriteNameHelper(Name);
switch (_jsonWriterSettings.OutputMode)
{
case JsonOutputMode.Strict:
var utcDateTimeFirst = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
_textWriter.Write($"\"{utcDateTimeFirst.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ")}\"");
break;
case JsonOutputMode.Shell:
default:
// use ISODate for values that fall within .NET's DateTime range, and "new Date" for all others
if (value >= BsonConstants.DateTimeMinValueMillisecondsSinceEpoch &&
value <= BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
{
var utcDateTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(value);
_textWriter.Write("ISODate(\"{0}\")", utcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFZ"));
}
else
{
_textWriter.Write("new Date({0})", value);
}
break;
}
State = GetNextState();
}
}
}
这就是魔法发生的地方。将整个类 JsonWriter 从 GitHub 复制到你自己的并给它一个新名称(扩展 BsonWriter
nad 实现所有方法)。现在,您可以在这里操作您希望如何序列化日期。相应地更改 WriteDateTime(long value)
。如您所见,在 case JsonOutputMode.Strict:
中,我将其更改为返回一个按我需要的方式格式化的 DateTime 对象。
最后,由于 MongoSerializer 具有名为 JsonWriterContext
的内部类,您需要创建自己的类并在 JsonWriter
中使用它(第 2 步)。
这是我的样子(你可以完整复制它):
using MongoDB.Bson.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fishing.MongoDB.Serializers
{
public class InternalJsonWriterContext
{
// private fields
private InternalJsonWriterContext _parentContext;
private ContextType _contextType;
private string _indentation;
private bool _hasElements = false;
// constructors
internal InternalJsonWriterContext(InternalJsonWriterContext parentContext, ContextType contextType, string indentChars)
{
_parentContext = parentContext;
_contextType = contextType;
_indentation = (parentContext == null) ? indentChars : parentContext.Indentation + indentChars;
}
// internal properties
internal InternalJsonWriterContext ParentContext
{
get { return _parentContext; }
}
internal ContextType ContextType
{
get { return _contextType; }
}
internal string Indentation
{
get { return _indentation; }
}
internal bool HasElements
{
get { return _hasElements; }
set { _hasElements = value; }
}
}
}
在你拥有一切之后,你将在 MongoCursorJsonConverter(第一步)中看到,在第二个 ToJsonMine()
方法中,我有这一行:
using (var bsonWriter = new JsonWriterMine(stringWriter, writerSettings ?? JsonWriterSettings.Defaults))
您只需将其替换为您在第 2 步中创建的自己的自定义类,它就会非常有效。
最后,您只需调用:
var lists = mongoListBatch.ToJson(settings);
它会序列化你在 WriteDate(long value)
关于c# - Mongo C# 驱动 toJson() DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46847042/
我正在尝试为基于 arm 的板交叉编译驱动程序。在 make 文件中,包含文件的搜索路径是主机内核的路径,即它指向 ubuntu 附带的 linux 头文件。我在主机系统(i7/ubuntu)上也有目
1、准备材料 开发板(正点原子stm32f407探索者开发板V2.4) 。 STM32CubeMX软件(Version 6.10.0) 。 野火DAP仿真器 。 keil µVis
是否可以通过 c# 应用程序“驱动”excel(即从 excel gui 下拉列表中选择某些内容,按下按钮并读取特定单元格的内容)? 这并不是真正用于测试,而是用于类似于 selenium 的数据报废
给定任何具有超过 5 个 View 和 View 模型的中间 MVVM 应用程序,是否有任何推荐的设计模式来说明如何为此类应用程序搭建脚手架? 现在我通常有一个在 App.OnStartup 中创建的
我想知道如何使用曼哈顿距离启发式来驱动 NxN 二维数组中的搜索。我有以下曼哈顿距离: private int manhattan(int[] pos, int tile) { int
我试图了解 CUmodule 在 CUDA 驱动程序 API 函数中实际上代表什么。 许多 CUDA 驱动程序 API 函数都有一个 CUmodule 句柄,但它是什么?它是引导驱动程序调用过程的 d
我正在尝试创建一个 java 程序,它将创建 excel 文件并将其上传到谷歌驱动器中。上传后我需要它来授予权限。我已经完成了所有这些,但问题在于尝试将 excel 文件转换为 google 文件,以
我正在拼命尝试从 Linux(Raspbian 内核 4.4.12-v7+)与使用 TIUSB3410 USB 部件的设备进行通信。 这是 dmesg 的输出: [ 2730.016013] usb
我有一个关于在 PCIe 上使用突发读写的问题。我有一个 fpga,它通过 PCIe 连接到 cpu。我有一个简单的驱动程序,仅用于测试。驱动程序向 FPGA 写入数据以及从 FPGA 读取数据。 f
我有大约 500 条通往特定页面的可能路径,我需要测试所有这些路径。该页面的每个路径看起来都类似于此(使用 PHP 网络驱动程序;通常有大约 10 个步骤): // Navigate to form
如果chrome驱动的版本和当前的chrome版本不同,我想写一个python代码,下载并运行与当前chrome版本匹配的chrome驱动。 这就是我一直在寻找的东西 driver = webdriv
我在 Centos 7 Linux 机器上尝试通过 pyodbc 连接到 SQL 数据库。我了解到您需要设置 DSN,您可以通过安装 freetds 驱动程序并执行以下操作来实现: import py
是否可以使用 NUnit 通过 NDepend 运行 CQL 查询?如果能够将 NDepend dll 包含在 UnitTests 库中并编写如下测试,那就太好了: [Test] public voi
我在 cassandra 中有巨大的表,超过 20 亿行并且还在增加。这些行有一个日期字段,它遵循日期桶模式以限制每一行。 即便如此,对于某个特定日期,我也有超过一百万条条目。 我想尽快读取和处理每一
考虑以下示例,其中一个模块的输出 (inner::out) 应该驱动两个输出(outer::out 和 outer::out2) 的上层层次: #include SC_MODULE(inner) {
我不确定是否可以有一个具有多个 MySQL 根的连接器。当我尝试只使用一根根时,它效果完美。我的有 2 个根的代码如下所示: [ 'locale' => 'es_ES.UTF-8',
我的桌面APP无法注册Mysql JDBC驱动 我下载mysql-connector-java-5.1.16.zip 解压mysql-connector-java-5.1.16-bin.jar并将其放
我有一个无限循环等待输入的 python 脚本,然后输入发生时做一些事情。我的问题是制作 python告诉 emacs 做某事。我只需要一些方法来发送 emacs 输入并让 emacs 评估该输入。
我最初问的没有明确说明我的问题/问题,所以我会更好地解释它。我有一个将 JDialog 设置为可见的 JButton。 JDialog 有一个 WindowListener 将其设置为在 window
假设“doc”是我想插入到 MongoDB 集合中的一些文档,而“collection”是我要将文档插入到的集合。 我有如下内容: try { WriteConcern wc = new Wr
我是一名优秀的程序员,十分优秀!