-
Notifications
You must be signed in to change notification settings - Fork 205
/
JsonStream.java
86 lines (72 loc) · 2.2 KB
/
JsonStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.bugsnag.android;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
public class JsonStream extends JsonWriter {
private final ObjectJsonStreamer objectJsonStreamer;
public interface Streamable {
void toStream(@NonNull JsonStream stream) throws IOException;
}
private final Writer out;
/**
* Constructs a JSONStream
*
* @param out the writer
*/
public JsonStream(@NonNull Writer out) {
super(out);
setSerializeNulls(false);
this.out = out;
objectJsonStreamer = new ObjectJsonStreamer();
}
// Allow chaining name().value()
@NonNull
public JsonStream name(@Nullable String name) throws IOException {
super.name(name);
return this;
}
/**
* This gives the Streamable the JsonStream instance and
* allows lets it write itself into the stream.
*/
public void value(@Nullable Streamable streamable) throws IOException {
if (streamable == null) {
nullValue();
return;
}
streamable.toStream(this);
}
/**
* Serialises an arbitrary object as JSON, handling primitive types as well as
* Collections, Maps, and arrays.
*/
public void value(@NonNull Object object) throws IOException {
objectJsonStreamer.objectToStream(object, this);
}
/**
* Writes a File (its content) into the stream
*/
public void value(@NonNull File file) throws IOException {
if (file == null || file.length() <= 0) {
return;
}
super.flush();
beforeValue(); // add comma if in array
// Copy the file contents onto the stream
Reader input = null;
try {
FileInputStream fis = new FileInputStream(file);
input = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
IOUtils.copy(input, out);
} finally {
IOUtils.closeQuietly(input);
}
out.flush();
}
}