Error in Java project: Type mismatch: 无法将元素类型从 Object 转换为 JSONObject

huangapple go评论64阅读模式
英文:

Error in Java project: Type mismatch: cannot convert from element type Object to JSONObject

问题

我遇到了这个错误:“类型不匹配:无法从元素类型Object转换为JSONObject”。

我不知道要更改什么,因为我的transactions是一个JSONObjects的JSONArray。是否有人知道为什么会出现这个问题以及如何修复它?谢谢!

   for (JSONObject transaction : transactions) {
        if (transaction.getString("direction").equals("OUT")) {
            int amount = transaction.getInt("amount");
            int rounded = (amount + 99) / 100 * 100;
            int roundUpAmount = rounded - amount;
            roundUpAmounts.add(roundUpAmount);
        }
    } 
   return roundUpAmounts;
}```

<details>
<summary>英文:</summary>

I am getting this error: &quot;Type mismatch: cannot convert from element type Object to JSONObject&quot;.

I don&#39;t know what to change because my transactions is a JSONArray of JSONObjects. Does anyone have an idea why this is happening and how to fix it? Thanks!

```	public ArrayList&lt;Integer&gt; roundUpArray(JSONArray transactions) {
		   for (JSONObject transaction : transactions) {
	            if (transaction.getString(&quot;direction&quot;).equals(&quot;OUT&quot;)) {
			   		int amount = transaction.getInt(&quot;amount&quot;);
	                int rounded = (amount + 99) / 100 * 100;
	                int roundUpAmount = rounded - amount;
	                roundUpAmounts.add(roundUpAmount);
	            }
	        } 
		   return roundUpAmounts;
	}


</details>


# 答案1
**得分**: 1

如果您明确转换数组的每个元素,它应该正常工作。
像这样:

```java
for (Object obj : transactions) {
    JSONObject transaction = (JSONObject) obj;
    if (transaction.getString("direction").equals("OUT")) {
        int amount = transaction.getInt("amount");
        int rounded = (amount + 99) / 100 * 100;
        int roundUpAmount = rounded - amount;
        roundUpAmounts.add(roundUpAmount);
    }
}
英文:

If you cast each element of the array explicitly, it should work.
Like this:

for (Object obj : transactions) {
    JSONObject transaction = (JSONObject) obj;
    if (transaction.getString(&quot;direction&quot;).equals(&quot;OUT&quot;)) {
        int amount = transaction.getInt(&quot;amount&quot;);
        int rounded = (amount + 99) / 100 * 100;
        int roundUpAmount = rounded - amount;
        roundUpAmounts.add(roundUpAmount);
    }
}

huangapple
  • 本文由 发表于 2023年4月4日 07:00:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定