如何使用Java在Couchdb中存储原始JSON [英] How to store raw JSON in Couchdb with java

查看:143
本文介绍了如何使用Java在Couchdb中存储原始JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在解析一个Web服务,该服务向我提供了Json Documents作为响应.我想使用Java将它们存储在CouchDb中,但是我找不到方法.使用用于Java的benchdb库(Ektorp,couchdb4j等),我只能将Java文档存储在数据库中,这意味着我必须将原始json转换为Java Document才能存储它们. 你有什么主意,我可以直接存储原始json吗? 提前非常感谢

I am currently parsing a web service that give me Json Documents as response. I want to store those in CouchDb using java, but I cannot find a way. With the couchdb library for java (Ektorp, couchdb4j etc...) I can only store java documents in the database, which would mean I have to transform my raw json to java Document in order to store them. Do you have any idea how i could directly store raw json ? Many thanks in advance

推荐答案

Ektop文档提供了

The Ektop documentation provides an example of updating a document using JSON stored in a file:

 File file = someMethodToGetFile();
 InputStream jsonInputStream = new FileInputStream(file);
 db.update("document_id",
           jsonInputStream,
           file.length(),
           null);

如果您的JSON位于Java程序的内存中(例如,作为String),则可以使用ByteArrayInputSteam:

Instead of using the FileInputStream, if your JSON is in memory in your java program (e.g. as a String), you could wrap the string in a ByteArrayInputSteam:

 String yourJsonString = ...

 InputStream jsonInputStream = new ByteArrayInputStream(yourJsonString.getBytes());
 db.update("document_id",
           jsonInputStream,
           file.length(),
           null);

或者,通过一个宁静的API访问CouchDB,因此您可以使用任何了解REST的Java库与CouchDB进行交互,例如,使用

Alternatively, CouchDB is accessed through a restful API so you can interact with CouchDB using any java library that understands REST, for example using Apache HttpClient:

String yourJsonString = ...

StringRequestEntity requestEntity = new StringRequestEntity(
    yourJsonString,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://couchdb.server/database");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

这篇关于如何使用Java在Couchdb中存储原始JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆