遍历嵌套的 JSON 数组并在 Java 中对字符串执行操作

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

Iterating through nested Json Array and performing operations on String Java

问题

[
    {
        "promise_detail": [
            {
                "promise_date": "15 OCT 2020",
                "promise_amount": "USD 1086.00",
                "status": "CANCELLED"
            }
        ],
        "promise_note": "hello"
    }
]
result = executeQueries.getPromiseHistoryDetails(promiseHistoryModel);
for (int n = 0; n < result.length(); n++) {
    JSONObject object = result.getJSONObject(n);
    JSONArray promiseDetailArray = object.getJSONArray("promise_detail"); // Access promise_detail array
    for (int k = 0; k < promiseDetailArray.length(); k++) {
        JSONObject promiseDetail = promiseDetailArray.getJSONObject(k);
        String promiseAmountStr = promiseDetail.getString("promise_amount"); // Access promise_amount string
        String formattedPromiseAmount = promiseAmountStr.replace("USD", "").trim(); // Remove "USD" and leading/trailing spaces
        Float amount = Float.parseFloat(formattedPromiseAmount);
        
        DecimalFormat df = new DecimalFormat("0.00");
        df.setMaximumFractionDigits(2);
        promiseDetail.put("promise_amount", "USD " + df.format(amount)); // Update promise_amount field
    }
}
英文:

I have json array in this format

    [
{
    &quot;promise_detail&quot;: [
        {
            &quot;promise_date&quot;: &quot;15 OCT 2020&quot;,
            &quot;promise_amount&quot;: &quot;USD 1086&quot;,
            &quot;status&quot;: &quot;CANCELLED&quot;
        }
    ],
    &quot;promise_note&quot;: &quot;hello&quot;
}

]

My requirement is i need to loop through Json array and format promise amount field to two decimal places which looks like "USD 1086.00"

Here is what i am trying to do

    result = executeQueries.getPromiseHistoryDetails(promiseHistoryModel);//Here result is same Json Array as shown above
    for (int n = 0; n &lt; result.length(); n++) {
			JSONObject object = result.getJSONObject(n);
			for(int k=0;k&lt;object.length();k++) {  //struck here
				String promiseAmount = object.getJSONObject(k);
                Float amount=Float.parseFloat(promiseAmount);
				if (object.get(&quot;promise_amount&quot;) != null) {
					DecimalFormat df = new DecimalFormat(&quot;0.00&quot;);
					df.setMaximumFractionDigits(2);
					result.getJSONObject(n).put(&quot;promise_amount&quot;, df.format(amount));
				}
			}
			
		}

But I am getting some issues.I am struck at this point.Can anyone suggest me how i can achieve this.This is my expected output

    [
{
    &quot;promise_detail&quot;: [
        {
            &quot;promise_date&quot;: &quot;15 OCT 2020&quot;,
            &quot;promise_amount&quot;: &quot;USD 1086.00&quot;,
            &quot;status&quot;: &quot;CANCELLED&quot;
        }
    ],
    &quot;promise_note&quot;: &quot;hello&quot;
}
]

答案1

得分: 1

似乎您在操作中混淆了 JSONArrayJSONObject。内部的循环应遍历 JSONArray 而不是 JSONObject

而且您给定的 JSON 字符串中 promise_amount 的格式是一个 String,所以您可以将 .00 直接附加到原始值,如下所示:

代码片段

for (int n = 0; n < result.length(); n++) {
    JSONArray object = result.getJSONObject(n).getJSONArray("promise_detail");
    for (int k = 0; k < object.length(); k++) {
        String promiseAmount = object.getJSONObject(k).getString("promise_amount");
        if (promiseAmount != null) {
            object.getJSONObject(k).put("promise_amount", String.format("%s.00", promiseAmount));
        }
    }
}
英文:

It seems you mixed up the operation of JSONArray with JSONObject. The inner for-loop is supposed to traverse a JSONArray rather than a JSONObject.

And the format of promise_amount in your given JSON string is a String, so you can just append .00 to the origin value as follows:

Code snippet

for (int n = 0; n &lt; result.length(); n++) {
    JSONArray object = result.getJSONObject(n).getJSONArray(&quot;promise_detail&quot;);
    for (int k = 0; k &lt; object.length(); k++) {
        String promiseAmount = object.getJSONObject(k).getString(&quot;promise_amount&quot;);
        if (promiseAmount != null) {
            object.getJSONObject(k).put(&quot;promise_amount&quot;, String.format(&quot;%s.00&quot;, promiseAmount));
        }
    }
}

huangapple
  • 本文由 发表于 2020年10月7日 21:05:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64244632.html
匿名

发表评论

匿名网友

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

确定