|
2 | 2 |
|
3 | 3 | import org.json.util.ALStack; |
4 | 4 |
|
| 5 | +import java.io.Closeable; |
5 | 6 | import java.io.IOException; |
6 | 7 | import java.util.HashSet; |
7 | 8 | import java.util.Set; |
@@ -59,7 +60,7 @@ of this software and associated documentation files (the "Software"), to deal |
59 | 60 | * @author JSON.org |
60 | 61 | * @version 2016-08-04 |
61 | 62 | */ |
62 | | -public class JSONWriter { |
| 63 | +public class JSONWriter implements Closeable { |
63 | 64 | private static final int initdepth = 16; |
64 | 65 |
|
65 | 66 | /** |
@@ -349,4 +350,55 @@ public JSONWriter value(long l) throws JSONException { |
349 | 350 | public JSONWriter value(Object object) throws JSONException { |
350 | 351 | return this.appendValue(object); |
351 | 352 | } |
| 353 | + |
| 354 | + /** |
| 355 | + * Append a sequence of values into an array. |
| 356 | + * |
| 357 | + * @param values The objects to append. They can be null, or a Boolean, Number, |
| 358 | + * String, JSONObject, or JSONArray, or an object that implements JSONString. |
| 359 | + * @return this |
| 360 | + * @throws JSONException If a value is out of place. For example, a value |
| 361 | + * occurs where a key is expected. |
| 362 | + */ |
| 363 | + public JSONWriter values(Iterable<?> values) throws JSONException { |
| 364 | + for(Object obj : values) { |
| 365 | + this.appendValue(obj); |
| 366 | + } |
| 367 | + return this; |
| 368 | + } |
| 369 | + |
| 370 | + /** |
| 371 | + * Append a sequence of key-value pairs into an object. |
| 372 | + * |
| 373 | + * @param kvPairs The objects to append. The values can be null, or a Boolean, |
| 374 | + * Number, String, JSONObject, or JSONArray, or an object that implements |
| 375 | + * JSONString. |
| 376 | + * @return this |
| 377 | + * @throws JSONException If a value is out of place. For example, a value |
| 378 | + * occurs where a key is expected. |
| 379 | + */ |
| 380 | + public JSONWriter entries(Map<String, ?> kvPairs) throws JSONException { |
| 381 | + for(Map.Entry<String, ?> entry : kvPairs.entrySet()) { |
| 382 | + this.key(entry.getKey()); |
| 383 | + this.appendValue(entry); |
| 384 | + } |
| 385 | + return this; |
| 386 | + } |
| 387 | + |
| 388 | + /** |
| 389 | + * Asserts the JSON writer is finished, and close any underlying |
| 390 | + * {@code Closeable} writer. |
| 391 | + * |
| 392 | + * @throws IOException the writer cannot be closed |
| 393 | + */ |
| 394 | + @Override |
| 395 | + public void close() throws IOException { |
| 396 | + if(!this.stack.isEmpty()) { |
| 397 | + throw new IOException("JSON stack is not empty"); |
| 398 | + } |
| 399 | + |
| 400 | + if(writer instanceof Closeable) { |
| 401 | + ((Closeable)writer).close(); |
| 402 | + } |
| 403 | + } |
352 | 404 | } |
0 commit comments