New APIs: JsonAdapter.toJsonObject, fromJsonObject.

https://github.com/square/moshi/issues/89
This commit is contained in:
jwilson 2017-01-24 22:11:31 -05:00
parent a90b6c7740
commit e54b023991
2 changed files with 59 additions and 0 deletions

View file

@ -54,6 +54,35 @@ public abstract class JsonAdapter<T> {
return buffer.readUtf8();
}
/**
* Encodes {@code value} as a Java model comprised of maps, lists, strings, numbers, booleans
* and nulls. The returned model is equivalent to calling {@link #toJson} to encode {@code value}
* as a JSON string, and then parsing that string without any particular type.
*/
public final Object toJsonObject(T value) {
ObjectJsonWriter writer = new ObjectJsonWriter();
try {
toJson(writer, value);
return writer.root();
} catch (IOException e) {
throw new AssertionError(e); // No I/O writing to an object.
}
}
/**
* Decodes a Java value from {@code object}, which must be a Java model comprised of maps, lists,
* strings, numbers, booleans and nulls. This is equivalent to encoding {@code object} to a JSON
* string, and then calling {@link #fromJson} to decode that string.
*/
public final T fromJsonObject(Object object) {
ObjectJsonReader reader = new ObjectJsonReader(object);
try {
return fromJson(reader);
} catch (IOException e) {
throw new AssertionError(e); // No I/O reading from an object.
}
}
/**
* Returns a JSON adapter equal to this JSON adapter, but with support for reading and writing
* nulls.

View file

@ -601,6 +601,36 @@ public final class MoshiTest {
.isEqualTo(new Pizza(18, true));
}
@Test public void classAdapterToObjectAndFromObject() throws Exception {
Moshi moshi = new Moshi.Builder().build();
Pizza pizza = new Pizza(15, true);
Map<String, Object> pizzaObject = new LinkedHashMap<>();
pizzaObject.put("diameter", 15L);
pizzaObject.put("extraCheese", true);
JsonAdapter<Pizza> jsonAdapter = moshi.adapter(Pizza.class);
assertThat(jsonAdapter.toJsonObject(pizza)).isEqualTo(pizzaObject);
assertThat(jsonAdapter.fromJsonObject(pizzaObject)).isEqualTo(pizza);
}
@Test public void customJsonAdapterToObjectAndFromObject() throws Exception {
Moshi moshi = new Moshi.Builder()
.add(Pizza.class, new PizzaAdapter())
.build();
Pizza pizza = new Pizza(15, true);
Map<String, Object> pizzaObject = new LinkedHashMap<>();
pizzaObject.put("size", 15L);
pizzaObject.put("extra cheese", true);
JsonAdapter<Pizza> jsonAdapter = moshi.adapter(Pizza.class);
assertThat(jsonAdapter.toJsonObject(pizza)).isEqualTo(pizzaObject);
assertThat(jsonAdapter.fromJsonObject(pizzaObject)).isEqualTo(pizza);
}
@Test public void indent() throws Exception {
Moshi moshi = new Moshi.Builder().add(Pizza.class, new PizzaAdapter()).build();
JsonAdapter<Pizza> jsonAdapter = moshi.adapter(Pizza.class);