Bson And Json

本文主要内容: 
一、讲述Bson和Json的区别 
二、Mongodb java api 中 Java对象和Bson对象的转换 


======================================== 

在研究Mongodb的时候,Mongodb的文档上说: 

引用
MongoDB uses BSON as the data storage and network transfer format for "documents".


Mongodb 使用BSON做为文档数据的存储以及网络传输格式。看到这,脑袋里蹦出个念头,怎么不是JSON 而是 BSON,BSON和JSON是什么关系,兄弟仍是父子关系?呵呵,是什么新鲜玩意儿?google了一把,首先看看wikipedia上怎么说: 

引用

BSON documents (objects) consist of a well ordered list of elements. Each element consists of a field name, a type, and a value. Field names are strings. Types include: 

    * string 
    * integer 
    * double 
    * date 
    * byte array (binary data) 
    * boolean (true and false) 
    * null 
    * BSON object 

This is nominally a superset of JSON types (JSON does not have a byte array type, for example), but because of length limitations, some valid JSON values (such as very long strings) are not valid BSON values. 


说白了,Bson的祖先仍是Json,只不过是加强了的Json,在数据类型上,比json支持的要普遍,并采用二进制方式编码,其余在表现形式上基本无他。 

Mongodb 采用Bson这种形式做为数据的存储形式,但其java 驱动感受用起来不爽,DBObject是进行存储的基类,要将Java 对象存入Mongo,需将java 对象的属性一个挨一个的put 进去(具体使用方法参见 http://www.mongodb.org/display/DOCS/Java+Tutorial ),感受用起来不是很舒服,不能直接将Java 对象存入。解决的办法我想能够有如下两个方法: 

1) 利用反射和Annotation(注释?),写个类直接将Java 对象转换成DBObject。这种方式实现起来应该不困难,可是嵌套对象的问题不太好弄。 

2)先将Java 对象转换成Json 字符串,而后利用Mongo的JSON 帮助类,直接将Json 字符串解析成DBObject,但不知道效率。 
相关文章
相关标签/搜索