【问题标题】:how to parse a json text file into BasicDBobject如何将 json 文本文件解析为 BasicDBobject
【发布时间】:2020-10-07 04:03:14
【问题描述】:
 public void process(FeedExchange exchange) throws Exception {
        List<BasicDBObject> collectionAttributes = (List<BasicDBObject>) exchange.getInput();
        for (BasicDBObject collectionAttribute : collectionAttributes) {
          if (collectionAttribute.get("name") != null) {
            String attributeName = collectionAttribute.getString("name");
            if (attributeName.equals(JobParamConstants.DEFAULT_LOCALE) || attributeName
              .equals(JobParamConstants.APPLICABLE_LOCALES)) {
              exchange.setProperty(attributeName, collectionAttribute.getString("_id"));
            }
          }

嗨,我需要为上述程序编写 junit 测试用例。所以我想将输入传递给 collectionAttributes。我的输入 json 是 GetCatalogCollectionResponse.json

{
"properties":[{
"attributeId":"123",
"value":"345"
},
{
"attributeId":"2345",
"value":"567"
}]
}

我想将此json解析为mongodb中的collectionAttributes。我尝试了以下代码

BasicDBObject DBObject = new BasicDBObject();
DBObject.parse(GetCatalogCollectionResponse.json);

但我遇到了一个错误。你能帮我吗?我是 java 的初学者,任何帮助将不胜感激..

【问题讨论】:

  • 方法DBObject.parse用于解析JSON 字符串

标签: java json mongodb junit


【解决方案1】:

您可以使用 Google 的 Gson 库从文件中解析 JSON,如下所示。解析后的对象可以映射到java.util.Map,您可以从中构建BasicDBObject

BufferedReader reader = new BufferedReader(new FileReader("test_file.json"));
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(reader, Map.class);
System.out.println(map);
// {properties=[{attributeId=123, value=345}, {attributeId=2345, value=567}]}

BasicDBObject obj = new BasicDBObject(map);
System.out.println(obj.toJson());
// {"properties": [{"attributeId": "123", "value": "345"}, {"attributeId": "2345", "value": "567"}]}

【讨论】:

  • 嗨,谢谢..json 文件存储在 ecllipse 的 src/test/resources 下,我在 src/java/test 文件夹中尝试了这一行。BufferedReader reader = new BufferedReader(new FileReader("src /test/resources/test_file.json"))。它显示 FileNotFoundException 异常。我怎么能通过这个 test_file.json ..纠正我我是 java 初学者.. –
  • 我用这个搜索字符串谷歌了:“如何在java中访问资源文件夹中的文件”,并找到了很多答案。我相信你会找到一些有用的东西来满足你的需要。
  • 另外,请参阅这篇有用的帖子:How much research effort is expected of Stack Overflow users?
  • 谢谢我找到了如何访问资源文件夹中文件的答案。
【解决方案2】:

我终于找到了我的问题的答案。

public class BasicDBObjectInput {

  public static String getInput(String resourceName) throws IOException {
    ClassLoader classLoader = BasicDBObjectInput.class.getClassLoader();
    File file = new File(classLoader.getResource(resourceName).getFile());
    String json = FileUtils.readFileToString(file, Charset.defaultCharset());

    return json;
  }

}

在这里我们可以像这样以字符串格式传递我们的 json 文件

String json = `BasicDBObjectInput.getInput("GetCatalogCollectionAttributeResponse.json"); BasicDBObject collectionAttributes = BasicDBObject.parse(json);`

希望对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 2018-11-01
    • 1970-01-01
    • 2015-04-26
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多