Mongo DB object Id deserializing using JSON serializer(Mongo DB对象ID使用JSON序列化程序反序列化)
问题描述
var docToJson = doc.ToJson<BsonDocument>();
story Featured = JsonConvert.DeserializeObject<story>(docToJson);
public class story
{
[JsonProperty("_id"), JsonConverter(typeof(ObjectIdConverter))]
public ObjectId Id { get; set; }
....
public class ObjectIdConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
return new ObjectId(token.ToObject<string>());
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ObjectId));
}
}
}
我被卡住了,我已经尝试了六种方法,但我仍然在使用 json 阅读器时遇到同样的错误,任何人有什么想法吗?
I'm stuck I've tried half a dozen methods, I'm still getting the same error with json reader, any ideas anyone?
最后一次尝试来自 SO*
JsonReader 异常
JsonReader Exception
解析值时遇到意外字符:O. 路径_id",第 1 行,位置 10.
Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10.
JSON 字符串如下所示:
The JSON string looks like this:
{
"_id": ObjectId("5378f94a3513fa3374be7e20"),
"cc": "GB",
"userName": "xyz ",
"userImage": "img/16.jpg",
"createdDate": ISODate("2014-05-18T18:17:46.983Z"),
"Headling": "Veniam, amet, incidunt veniam, ipsam nostrud natus exercitationem consectetur, eos dolorem. ",
"subheading": "Veniam, amet, incidunt veniam, ipsam nostrud. "
}
推荐答案
您收到此错误是因为 _id 属性的值不符合 JSON 标准(请参阅 JSON.org).JSON 值必须是以下之一:
You are getting this error because the value for the _id property does not conform to the JSON standard (see JSON.org). JSON values must be one of the following:
- 一个字符串(以引号
"开头和结尾) - 一个数字
- 一个对象(以花括号
{和}开始和结束) - 一个数组(以方括号
[和]开始和结束) - 关键字
true、false或null
- a string (starts and ends with quote marks
") - a number
- an object (starts and ends with curly braces
{and}) - an array (starts and ends with square brackets
[and]) - the keywords
true,false, ornull
值 ObjectId("5378f94a3513fa3374be7e20") 似乎是一个无效的函数.ISODate("2014-05-18T18:17:46.983Z") 值也有同样的问题.如果您想使用 JSON.net 解析它,您将需要以某种方式更改您的 JSON 以符合标准.
The value ObjectId("5378f94a3513fa3374be7e20") appears to be a function, which is not valid. The value ISODate("2014-05-18T18:17:46.983Z") has the same problem. You will need to somehow change your JSON to meet the standard if you want to parse it using JSON.net.
这篇关于Mongo DB对象ID使用JSON序列化程序反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mongo DB对象ID使用JSON序列化程序反序列化
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
