如何使用 java 在 Couchdb 中存储原始 JSON
How to store raw JSON in Couchdb with java
我目前正在解析一个 Web 服务,它给我 Json 文档作为响应。我想使用 java 将它们存储在 CouchDb 中,但我找不到方法。使用 java 的 couchdb 库(Ektorp、couchdb4j 等...)我只能在数据库中存储 java 文档,这意味着我必须将原始 json 转换为 java 文件以便存储它们。
你知道我如何直接存储原始 json 吗?
非常感谢
Ektop 文档提供 an example 使用存储在文件中的 JSON 更新文档:
File file = someMethodToGetFile();
InputStream jsonInputStream = new FileInputStream(file);
db.update("document_id",
jsonInputStream,
file.length(),
null);
如果您的 JSON 在您的 java 程序的内存中(例如作为字符串),而不是使用 FileInputStream
,您可以将字符串包装在 ByteArrayInputSteam
:
String yourJsonString = ...
InputStream jsonInputStream = new ByteArrayInputStream(yourJsonString.getBytes());
db.update("document_id",
jsonInputStream,
file.length(),
null);
或者,通过 restful API 访问 CouchDB,因此您可以使用任何理解 REST 的 java 库与 CouchDB 交互,例如使用 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);
我目前正在解析一个 Web 服务,它给我 Json 文档作为响应。我想使用 java 将它们存储在 CouchDb 中,但我找不到方法。使用 java 的 couchdb 库(Ektorp、couchdb4j 等...)我只能在数据库中存储 java 文档,这意味着我必须将原始 json 转换为 java 文件以便存储它们。 你知道我如何直接存储原始 json 吗? 非常感谢
Ektop 文档提供 an example 使用存储在文件中的 JSON 更新文档:
File file = someMethodToGetFile();
InputStream jsonInputStream = new FileInputStream(file);
db.update("document_id",
jsonInputStream,
file.length(),
null);
如果您的 JSON 在您的 java 程序的内存中(例如作为字符串),而不是使用 FileInputStream
,您可以将字符串包装在 ByteArrayInputSteam
:
String yourJsonString = ...
InputStream jsonInputStream = new ByteArrayInputStream(yourJsonString.getBytes());
db.update("document_id",
jsonInputStream,
file.length(),
null);
或者,通过 restful API 访问 CouchDB,因此您可以使用任何理解 REST 的 java 库与 CouchDB 交互,例如使用 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);