简体   繁体   English

如何将json文本文件解析为BasicDBobject

[英]how to parse a json text file into BasicDBobject

 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"));
            }
          }

hi i need to write junit testcase for above program..so i want to pass input to collectionAttributes.my input json is GetCatalogCollectionResponse.json嗨,我需要为上述程序编写junit测试用例..所以我想将输入传递给collectionAttributes.我的输入json是GetCatalogCollectionResponse.json

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

i want to parse this json to collectionAttributes in mongodb.i tried the following code我想将此 json 解析为 mongodb 中的 collectionAttributes。我尝试了以下代码

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

but i got an error.could you help me i am beginner to java,any help would be appreciated..但我有一个错误。你能帮我吗?我是 Java 初学者,任何帮助将不胜感激..

You can use the Google's Gson library to parse the JSON from a file as shown below.您可以使用 Google 的Gson库从文件中解析 JSON,如下所示。 The parsed object can be mapped to a java.util.Map , from which you can build the BasicDBObject .解析的对象可以映射到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"}]}

finally i found answer for my question.最后我找到了我的问题的答案。

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;
  }

}

here we can pass our json file in string format like this在这里我们可以像这样以字符串格式传递我们的 json 文件

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

hope it will helps somebody.希望它会帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM