java json to bson_JSON BSON 效率比较

慕嘉运
2023-12-01

对于基础知识的学习和理解,请参看两者的官方网站:

这里主要介绍两者对于POJO的转换方式以及效率比对。

1. JSON

Jackson提供三种方法处理JSON:

Streaming API :reads and writes JSON content as discrete events. 该方式效率最高(相比于其他两种方式)

Tree Model:provides a mutable in-memory tree representation of a JSON document,该方式最灵活

Data Binding:couverts JSON to and from POJOs based either on property accessor conventions or annotations. 这种方式通常是最方便的。

先提供一个实体类 -- User entity (User.java 代码参看附件),JSON表示如下:

{

"name" : { "first" : "Joe", "last" : "Sixpack" },

"gender" : "MALE",

"verified" : false,

"userImage" : "Rm9vYmFyIQ=="

}

JSON 和 POJO的转换程序如下:

public class JsonPojoMapper {

private static ObjectMapper m = new ObjectMapper();

private static JsonFactory jf = new JsonFactory();

public static Object fromJson(String jsonAsString, Class pojoClass) throws Exception {

return m.readValue(jsonAsString, pojoClass);

}

public static String toJson(Object pojo, boolean prettyPrint)

throws IOException {

StringWriter sw = new StringWriter();

JsonGenerator jg = jf.createGenerator(sw);

if (prettyPrint) {

jg.useDefaultPrettyPrinter();

}

m.writeValue(jg, pojo);

return sw.toString();

}

}

2. BSON

BSON short for Binary JSON, is a binary-encoded serialization of JSON-like documents.

BSON目前主要用于MongoDB中,是MongoDB的数据存储格式。

BSON文档到字符文档的转换类似于JSON,具体可参考下面的测试代码

3. performance测试

更高的效率是BSON的主要目标之一,但究竟和JSON比效率如何?

测试场景:100W条数据的转换,从POJO转换为JSON/BSON, 然后再转换为POJO

测试代码:

public class PerformanceBsonJson {

private User src = new User();

private User dst = new User();

@Before

public void setUP() {

src.setUserName("ca bj test");

src.setPassword("ca admin");

}

@Test

public void testJson() throws Exception {

long begin = System.currentTimeMillis();

for (int i = 0; i < 1000000; i++) {

String jsonString = JsonPojoMapper.toJson(src, true);

dst = (User) JsonPojoMapper.fromJson(jsonString, User.class);

}

long end = System.currentTimeMillis();

System.out.println("Transfer Json cost is: " + (end - begin) + "ms");

}

@Test

public void testBson() throws JsonProcessingException, JsonMappingException, IOException {

BsonFactory fac = new BsonFactory();

fac.enable(BsonGenerator.Feature.ENABLE_STREAMING);

ObjectMapper mapper = new ObjectMapper(fac);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

long begin = System.currentTimeMillis();

for(int i=0; i<1000000; i++){

mapper.writeValue(baos, src);

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

dst = mapper.readValue(bais, User.class);

baos.reset();

}

long end = System.currentTimeMillis();

System.out.println("Transfer Bson cost is: " + (end-begin) +"ms");

}

}

测试结果:

Transfer Bson cost is: 4939ms

Transfer Json cost is: 2339ms

PS:测试结果根据选用第三方转换类库,以及转换方式不同会有不同结果。

但这种场景至少说明,在某些情况下JSON比BSON效率更高。

详细可执行代码参考附件内容。

 类似资料: