Home > database >  Removing escaped strings in Java JSON Object
Removing escaped strings in Java JSON Object

Time:10-12

I have a Java program that will dynamically build queries for ElasticSearch given some params. Currently, the way I have this built escapes the strings because the JsonObject as a part of Google's GSON library requires a string to be passed to append JSON.

The output from the below methods is the following:

{
   "query":{
      "bool":{
         "filter":[
            {
               "exists":"{\"field\":\"user_id\"}"
            },
            {
               "exists":"{\"field\":\"campaign_id\"}"
            }
         ]
      }
   }
}

As you can see, the exists values are escapes and ElasticSearch throws a fit about this. How can I achieve this result without having the escapes strings?

JsonObject buildQuery() {
    JsonObject request = new JsonObject();

    // build the terms query
    JsonArray termsArr = new JsonArray();
    termsArr.add(buildFilterQueryForField("user_id"));
    termsArr.add(buildFilterQueryForField("campaign_id"));
    JsonObject terms = JsonHelper.createObject("bool.filter", termsArr);
    request.add("query", terms);

    return request;
}

Below is the code for the buildFilterQueryForField(*). In this method, i've tried to use a regex to remove these, however this regex doesn't give me the result i'm after.

static JsonObject buildFilterQueryForField(String fieldName) {
    JsonObject builder = new JsonObject();
    JsonObject nestedObj = new JsonObject();
    nestedObj.addProperty("field", fieldName);
    builder.addProperty("exists", nestedObj.toString().replaceAll("\\\\", ""));
    return builder;
}

The end goal for this is the following:

{
   "query":{
      "bool":{
         "filter":[
            {
                "exists": { "field": "user_id" }
            },
            {
                "exists": { "field": "campaign_id" }
            },
         ]
      }
   }
}

CodePudding user response:

those escapes are required because you are actually embedding another json object inside the string value for the exists field. instead of using addProperty, you should be using builder.add("exists", nestedObj) just like you do elsewhere.

  • Related