Deepika
Deepika

Reputation: 1

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

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

i want to parse this json to collectionAttributes in mongodb.i tried the following code

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..

Upvotes: 0

Views: 174

Answers (2)

Deepika
Deepika

Reputation: 1

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

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

hope it will helps somebody.

Upvotes: 0

prasad_
prasad_

Reputation: 14287

You can use the Google's Gson library to parse the JSON from a file as shown below. The parsed object can be mapped to a java.util.Map, from which you can build the 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"}]}

Upvotes: 1

Related Questions