简体   繁体   中英

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?

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.*"));

Try this,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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