简体   繁体   English

如何反序列化json对象?

[英]How to deserialize json object?

I know that normally the method Newtonsoft.Json.JsonConvert.DeserializeObject is used. 我知道通常使用Newtonsoft.Json.JsonConvert.DeserializeObject方法。 However in this case I do a serialization, followed by a deserialization which doesn't work. 但是,在这种情况下,我先进行了序列化,然后再进行了反序列化,但无法进行。

static public void mess(test message)
{
  try
  {
    test temp = new test(id); // The only thing I don't show is that I obtain a valid ObjectId in id
    string messageSerialized = Newtonsoft.Json.JsonConvert.SerializeObject(temp);
    Newtonsoft.Json.JsonConvert.DeserializeObject<test>(messageSerialized);
  }
  catch (Exception e)
  {
    Console.WriteLine(e.Message);
  }
}

I get the following exception: Error converting value "57ab57ba86597bac513ce130" to type MongoDB.Bson.ObjectId'. 我收到以下异常:将值“ 57ab57ba86597bac513ce130”转换为MongoDB.Bson.ObjectId'类型时出错。 Path 'a', line 1, position 31." 路径“ a”,第1行,位置31。”

I get that the problem is the type, however how could it serialize the type but not be able to deserialize it? 我知道问题是类型,但是如何才能序列化类型却不能反序列化呢?

Structure of test: 测试结构:

   public class test
    {
        public MongoDB.Bson.ObjectId a;

        public test(MongoDB.Bson.ObjectId b)
        {
            a = b;
        }
    }


messageSerialized = "{\"a\":\"57ab57ba86597bac513ce130\"}"

Error converting value "here is an object ID" to type MongoDB.Bson.ObjectId'. 将值“这里是对象ID”转换为MongoDB.Bson.ObjectId'时出错。

Yes, look at the error and as can see it's trying to deserialize the string "here is an object ID" to Bson.ObjectId which will never succeed. 是的,请查看该错误,可以看到它正在尝试将字符串"here is an object ID"反序列化为Bson.ObjectId ,但此操作将永远不会成功。 You should post your serialized JSON string along with structure of BrowsersObj . 您应该发布序列化的JSON字符串以及BrowsersObj结构。

Per your latest edit: "57ab57ba86597bac513ce130" is not a MongoDB ObjectId rather it's a string. 根据您的最新编辑: "57ab57ba86597bac513ce130"不是MongoDB ObjectId,而是一个字符串。 Check your MongoDB collection and most probably you are not storing the _id as ObjectID rather you have overwritten them to store as string 检查您的MongoDB集合,很可能您没有将_id存储为ObjectID而是已经覆盖了它们以存储为string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM