Mongo DB对象ID使用JSON序列化程序反序列化

Mongo DB object Id deserializing using JSON serializer(Mongo DB对象ID使用JSON序列化程序反序列化)

本文介绍了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:

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

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

本文标题为:Mongo DB对象ID使用JSON序列化程序反序列化

基础教程推荐