NitZRobotKoder
NitZRobotKoder

Reputation: 1096

How to avoid quotes around string values while creating JSONObject

I am trying to create JSON query string for MongoDB, In order to support regular expression I need to create JSON string that has values without quotes. How do accomplish this in java,

Here is the example of what I am trying to do,

  JSONObject obj= new JSONObject();
  String title = "gro";
  obj.put("title", "/.*" + title + ".*/");

Result is

   {"title ":"/.*gro.*/"}

Above is no longer treated as a regular expression by MongoDB. What i wanted is,

   {"title ":/.*gro.*/}

So that MongoDB treats it as a regular expression. Is there any way to accomplish this in java?

Upvotes: 1

Views: 810

Answers (2)

Sudhakar
Sudhakar

Reputation: 4873

Try this,

  JSONObject obj= new JSONObject();
  String title = "gro";
  String startExpr = "/.*";
  String endExpr = ".*/";

  obj.put("title", startExpr  + title + endExpr );

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312095

The / delimited regular expression syntax is a JavaScript construct. In Java you have to use java.util.regex.Pattern like this:

BasicDBObject query = new BasicDBObject("title", Pattern.compile(".*gro.*"));

Upvotes: 1

Related Questions