使用 JSON 序列化程序反序列化 Mongo DB 对象 ID [英] Mongo DB object Id deserializing using JSON serializer

查看:34
本文介绍了使用 JSON 序列化程序反序列化 Mongo DB 对象 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 时遇到同样的错误,有人有任何想法吗?

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:

  • 一个字符串(以引号"开头和结尾)
  • 一个数字
  • 一个对象(以花括号{}开头和结尾)
  • 一个数组(以方括号[]开始和结束)
  • 关键字truefalsenull
  • 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, or null

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.

这篇关于使用 JSON 序列化程序反序列化 Mongo DB 对象 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆