gpt4 book ai didi

c# - 使用 JSON 序列化器反序列化 Mongodb 对象 ID

转载 作者:IT老高 更新时间:2023-10-28 13:36:24 26 4
gpt4 key购买 nike

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 reader 相同的错误,有人有什么想法吗?

上次尝试此操作来自 SO *

JsonReader Exception

Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10.

JSON 字符串如下所示:

{
"_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 值必须是以下之一:

  • 字符串(以引号 " 开头和结尾)
  • 一个数字
  • 一个对象(以大括号 {} 开头和结尾)
  • 数组(以方括号 [] 开头和结尾)
  • 关键字 truefalsenull

ObjectId("5378f94a3513fa3374be7e20") 似乎是一个无效的函数。值 ISODate("2014-05-18T18:17:46.983Z") 也有同样的问题。如果您想使用 JSON.net 解析 JSON,则需要以某种方式更改 JSON 以满足标准。

关于c# - 使用 JSON 序列化器反序列化 Mongodb 对象 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com