简体   繁体   English

JSONObject.toString类型不匹配无法从JSONString转换为JSONObject

[英]JSONObject.toString Type mismatch cannot convert from JSONString to JSONObject

Per the API we should be able to do this. 根据API,我们应该能够做到这一点。

http://www.json.org/javadoc/org/json/JSONObject.html#toString() 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. 显然,我们已定义了有效负载,它是一个JSONObject。 Why isn't this working and what should be done? 为什么这不起作用,应该做什么?

Your method declares that it returns a value of type JSONObject . 您的方法声明它返回JSONObject类型的值。 But this: 但是这个:

return payload.toString();

returns a value of type String . 返回String类型的值。 There's no implicit conversion from String to JSONObject , hence the compile-time error. 没有从StringJSONObject隐式转换,因此编译时错误。

If you really want a string, change the method return type. 如果您确实需要字符串,请更改方法返回类型。 If you really want a JSONObject , just change the return statement to: 如果你真的想要一个JSONObject ,只需将return语句改为:

return payload;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JSONObject.toString() 返回 OutOfMemoryError - JSONObject.toString() returns OutOfMemoryError JSONObject.toString() 正在创建 OutOfMemoryError - JSONObject.toString() is creating OutOfMemoryError 类型不匹配:无法从 org.codehaus.jettison.json.JSONObject 转换为 org.json.JSONObject - Type mismatch: cannot convert from org.codehaus.jettison.json.JSONObject to org.json.JSONObject 类型不匹配:无法从org.json.JSONObject转换为org.json.simple.JSONObject - Type mismatch: cannot convert from org.json.JSONObject to org.json.simple.JSONObject JSONObject.toString:如何不转义斜杠 - JSONObject.toString: how NOT to escape slashes 如何将 JavaObject 从 POJO 转换为 JSONString/JSONObject - How to convert JavaObject from POJO to JSONString/JSONObject 如何在 Java 中将 jsonString 转换为 JSONObject - How to convert jsonString to JSONObject in Java JSONObject.toString(“ variable”)声明字段不存在,即使从浏览器api调用粘贴复制后也是如此 - JSONObject.toString(“variable”) claims field is not there even when copy pasted from browser api call Java: JSONObject.toString() - 在冒号后添加额外的空格 (&quot;:&quot; -&gt; &quot;: &quot;) - Java: JSONObject.toString() - adding extra space after colon (":" -> ": ") JSONObject.toString(int)如何抛出JSONException? - How can JSONObject.toString(int) throw JSONException?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM