JToken和BsonValue对象的相互转换
莫问今朝
发布
于
2019-03-01 15:38:53
发布
于
2019-03-01 15:38:53
/// <summary>
/// JObject和BsonValue之间的
/// </summary>
public static class AdapterExtensions
/// <summary>
/// </summary>
/// <param name="object"></param>
/// <returns></returns>
public static BsonDocument ToBsonDocument(this JObject @object)
IDictionary<String, Object> elems = new Dictionary<String, Object>(); ;
foreach (var item in @object)
elems[item.Key] = ToBsonValue(item.Value);
return new BsonDocument(elems);
public static BsonArray ToBsonArray(this JArray array)
IList<BsonValue> bvs = new List<BsonValue>();
foreach (JToken item in array)
bvs.Add(ToBsonValue(item));
return new BsonArray(bvs);
private static BsonValue ToBsonValue(this JToken val)
if (val is JArray)
return ToBsonArray(val as JArray);
if (val is JObject)
return ToBsonDocument(val as JObject);
return ToBasicValue(val);
private static BsonValue ToBasicValue(JToken @object)
switch (@object.Type)
case JTokenType.Integer:
return BsonValue.Create(@object.ToObject<Int32>());
case JTokenType.Float:
return BsonValue.Create(@object.ToObject<float>());
case JTokenType.String:
return BsonValue.Create(@object.ToObject<String>());
case JTokenType.Boolean:
return BsonValue.Create(@object.ToObject<Boolean>());
case JTokenType.Date:
return BsonValue.Create(@object.ToObject<DateTime>());
case JTokenType.Guid:
return BsonValue.Create(@object.ToObject<Guid>());
case JTokenType.Null:
return null;
default:
throw new Exception("");
public static JObject ToJObject(this BsonDocument bsonDocument)
JObject elems = new JObject();
foreach (var item in bsonDocument)
Object data = item.Value;
elems[item.Name] = ToJsonValue(item.Value);
return elems;
public static JArray ToJArray(this BsonArray array)
IList<JToken> bvs = new List<JToken>();
foreach (var item in array)
bvs.Add(ToJsonValue(item));
return new JArray(bvs);
private static JToken ToJsonValue(this BsonValue val)
if (val is BsonArray)
return ToJArray(val as BsonArray);
if (val is BsonDocument)