Mongo DB object Id deserializing using JSON serializer

∥☆過路亽.° 提交于 2020-01-19 16:23:08

问题


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));
        }
      }
    }

I'm stuck I've tried half a dozen methods, I'm still getting the same error with json reader, any ideas anyone?

Last tried this from SO*

JsonReader Exception

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

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. "
}

回答1:


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:

  • 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

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.



来源:https://stackoverflow.com/questions/23726939/mongo-db-object-id-deserializing-using-json-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!