简体   繁体   中英

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?

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;

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