JSONObject.toString Type mismatch cannot convert from JSONString to JSONObject

Per the API we should be able to do this.

http://www.json.org/javadoc/org/json/JSONObject.html#toString()

  @Override
  public JSONObject buildPayload(BuildData buildData, String jenkinsUrl, List<String> logLines) {
    JSONObject payload = new JSONObject();
    payload.put("data", buildData.toJson());
    payload.put("message", logLines);
    payload.put("source", "jenkins");
    payload.put("source_host", jenkinsUrl);
    payload.put("@timestamp", buildData.getTimestamp());
    payload.put("@version", 1);

    // we need to flatten payload from JSONObject to String
    return payload.toString();
  }

Clearly, we have defined payload and it is a JSONObject. Why isn't this working and what should be done?

Jon Skeet
people
quotationmark

Your method declares that it returns a value of type JSONObject. But this:

return payload.toString();

returns a value of type String. There's no implicit conversion from String to JSONObject, hence the compile-time error.

If you really want a string, change the method return type. If you really want a JSONObject, just change the return statement to:

return payload;

people

See more on this question at Stackoverflow