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"));
}
}嗨,我需要为上面的program..so编写junit测试用例,我想传递输入到collectionAttributes.my输入,json是GetCatalogCollectionResponse.json
{
"properties":[{
"attributeId":"123",
"value":"345"
},
{
"attributeId":"2345",
"value":"567"
}]
}我想在mongodb.i中将这个json解析为collectionAttributes。
BasicDBObject DBObject = new BasicDBObject();
DBObject.parse(GetCatalogCollectionResponse.json);但是我得到了一个error.could你帮我我是java的初学者,任何帮助都将不胜感激..
发布于 2020-10-07 14:30:33
您可以使用Google库从文件中解析Gson,如下所示。解析后的对象可以映射到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"}]}发布于 2020-11-30 16:12:40
我终于找到了我的问题的答案。
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);`希望它能对某些人有所帮助。
https://stackoverflow.com/questions/64237023
复制相似问题