Search code examples
beanshell

beanShell json body for post method on Jmeter


can anyone help to add escape quotation marks with slash like \" on this son body:

    {
  "firstName": "teo",
  "lastName": "leo",
  "companyName": "abc",
  "restaurantId": "54d34443e4b0382b3208703d",
  "phones": [
    {
      "label": "Mobile",
      "value": "123456789",
      "countryCode": "+123",
      "isPrimary": true
    }
  ],
  "addresses": "haha"
}

i've tried with this one but beanShell PreProcessor can't accept it

String formvalues = "{\"firstName\": \"teo\",\"lastName\": \"leo\",\"companyName\": \"abc\",\"restaurantId\": \"54d34443e4b0382b3208703d\",\"phones\": [{\"label\":\"Mobile\",\"value\": \"123456789\",\"countryCode\": \"+123\",\"isPrimary\": true}],\"addresses\": \"haha\"}"

thanks you so much!


Solution

  • If you want to keep formatting:

    String formvalues = "{\n" +
            "  \"firstName\": \"teo\",\n" +
            "  \"lastName\": \"leo\",\n" +
            "  \"companyName\": \"abc\",\n" +
            "  \"restaurantId\": \"54d34443e4b0382b3208703d\",\n" +
            "  \"phones\": [\n" +
            "    {\n" +
            "      \"label\": \"Mobile\",\n" +
            "      \"value\": \"123456789\",\n" +
            "      \"countryCode\": \"+123\",\n" +
            "      \"isPrimary\": true\n" +
            "    }\n" +
            "  ],\n" +
            "  \"addresses\": \"haha\"\n" +
            "}";
    

    If you want single line (mind that Content-Length will be different)

    String formvalues = "{\"firstName\":\"teo\",\"lastName\":\"leo\",\"companyName\":\"abc\",\"restaurantId\":\"54d34443e4b0382b3208703d\",\"phones\":[{\"label\":\"Mobile\",\"value\":\"123456789\",\"countryCode\":\"+123\",\"isPrimary\":true}],\"addresses\":\"haha\"}";
    

    Full code to generate the body and add it as parameter:

    import org.apache.jmeter.config.Arguments;
    import org.apache.jmeter.protocol.http.util.HTTPArgument;
    
    String formvalues = "{\n" +
               "  \"firstName\": \"teo\",\n" +
               "  \"lastName\": \"leo\",\n" +
               "  \"companyName\": \"abc\",\n" +
               "  \"restaurantId\": \"54d34443e4b0382b3208703d\",\n" +
               "  \"phones\": [\n" +
               "    {\n" +
               "      \"label\": \"Mobile\",\n" +
               "      \"value\": \"123456789\",\n" +
               "      \"countryCode\": \"+123\",\n" +
               "      \"isPrimary\": true\n" +
               "    }\n" +
               "  ],\n" +
               "  \"addresses\": \"haha\"\n" +
               "}";
    
    Arguments arguments = new Arguments();
    arguments.addArgument(new HTTPArgument("",formvalues));       
    sampler.setArguments(arguments);
    

    JavaDoc on relevant classes:

    See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on Beanshell scripting in JMeter.