我有一个 JSON 数组{"payment":[{"a":"11","b":"21","c":"34","d":"0"},{"a":"54","b":"66","c":"21","d":"76"},{"a":"34","b":"23","c":"43","d":"88"}]}
,我已经迭代数组中的每个项目以形成一个字符串。
我试图丢弃数组中“d”等于 0(零)的数组对象。例如:{"a":"11","b":"21","c":"34","d":"0"}
.
我在每个项目之间添加了一个分号,并在每个数组对象中添加了一个逗号:{54;66;21;76,34;23;43;88}
。
但我需要这样的最终结果{"payment":"54;66;21;76,34;23;43;88"}
:
代码:
public class TestJson {
public static void main(String[] args) {
String jsonArray = "{\"payments\":[{\"a\":\"11\",\"b\":\"21\",\"c\":\"34\",\"d\":\"0\"},{\"a\":\"54\",\"b\":\"66\",\"c\":\"21\",\"d\":\"76\"},{\"a\":\"34\",\"b\":\"23\",\"c\":\"43\",\"d\":\"88\"}]}";
JsonObject jsonObject2 = new Gson().fromJson(jsonArray, JsonObject.class);
String key = "";
JsonObject innerObj = new JsonObject();
StringBuilder joinBuilder = new StringBuilder();
JsonArray paymentsArray = jsonObject2.getAsJsonArray("payments");
for (JsonElement jsonElement : paymentsArray) {
Set<Entry<String, JsonElement>> elemEntry = ((JsonObject) jsonElement).entrySet();
Iterator<Entry<String, JsonElement>> itr = elemEntry.iterator();
String finalVal = "";
String semiColon = "";
while (itr.hasNext()) {
Entry<String, JsonElement> entry = itr.next();
key = entry.getKey();
JsonPrimitive valuePrim = entry.getValue().getAsJsonPrimitive();
if (valuePrim.isString()) {
finalVal = valuePrim.getAsString();
}
joinBuilder.append(semiColon).append(finalVal);
semiColon = ";";
}
joinBuilder.append(",");
}
innerObj.addProperty("payments", joinBuilder.toString());
System.out.println(innerObj.toString());
}}
输出:{"payments":"11;21;34;0,54;66;21;76,34;23;43;88,"}
但我需要删除字符串末尾的逗号,如果“d”字段为 0,则丢弃整个数组对象。前任:{11;21;34;0}
湖上湖
相关分类