Stream to a DOM

This commit is contained in:
Jesse Wilson 2011-09-30 06:32:33 +00:00
parent d26c818918
commit 364de80611
3 changed files with 13 additions and 8 deletions

View File

@ -51,8 +51,11 @@ public final class JsonElementWriter extends JsonWriter {
}
public JsonElement get() {
if (stack.isEmpty()) {
return JsonNull.INSTANCE; // TODO: is this really what we want?
}
if (stack.size() != 1) {
throw new IllegalStateException();
throw new IllegalStateException("Expected one JSON element but was " + stack);
}
return stack.get(0);
}
@ -129,6 +132,9 @@ public final class JsonElementWriter extends JsonWriter {
}
@Override public JsonWriter value(String value) throws IOException {
if (value == null) {
return nullValue();
}
put(new JsonPrimitive(value));
return this;
}
@ -154,6 +160,9 @@ public final class JsonElementWriter extends JsonWriter {
}
@Override public JsonWriter value(Number value) throws IOException {
if (value == null) {
return nullValue();
}
put(new JsonPrimitive(value));
return this;
}

View File

@ -18,11 +18,9 @@ package com.google.gson.internal.bind;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
@ -56,13 +54,10 @@ public abstract class TypeAdapter<T> {
public JsonElement toJsonElement(T src) {
try {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
JsonElementWriter jsonWriter = new JsonElementWriter();
jsonWriter.setLenient(true);
write(jsonWriter, src);
JsonReader reader = new JsonReader(new StringReader(stringWriter.toString()));
reader.setLenient(true);
return Streams.parse(reader);
return jsonWriter.get();
} catch (IOException e) {
throw new JsonIOException(e);
}

View File

@ -23,6 +23,7 @@ public final class JsonElementWriterTest extends TestCase {
// TODO: more tests
// TODO: close support
// TODO: figure out what should be returned by an empty writer
public void testArray() throws IOException {
JsonElementWriter writer = new JsonElementWriter();