Skip to content

Commit 978ce40

Browse files
authored
Write values, entries, and implement Closeable
1 parent 0636808 commit 978ce40

1 file changed

Lines changed: 53 additions & 1 deletion

File tree

‎JSONWriter.java‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import org.json.util.ALStack;
44

5+
import java.io.Closeable;
56
import java.io.IOException;
67
import java.util.HashSet;
78
import java.util.Set;
@@ -59,7 +60,7 @@ of this software and associated documentation files (the "Software"), to deal
5960
* @author JSON.org
6061
* @version 2016-08-04
6162
*/
62-
public class JSONWriter {
63+
public class JSONWriter implements Closeable {
6364
private static final int initdepth = 16;
6465

6566
/**
@@ -349,4 +350,55 @@ public JSONWriter value(long l) throws JSONException {
349350
public JSONWriter value(Object object) throws JSONException {
350351
return this.appendValue(object);
351352
}
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+
}
352404
}

0 commit comments

Comments
 (0)