Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fail gracefully when a primitive value is absent. #1445

Merged
merged 1 commit into from Dec 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -21,6 +21,7 @@

import com.squareup.moshi.FromJson;
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonDataException;
import com.squareup.moshi.JsonQualifier;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
Expand Down Expand Up @@ -248,4 +249,46 @@ boolean booleanFromJson(JsonReader reader) throws IOException {
}

public static record BooleanRecord(boolean value) {}

@Test
public void absentPrimitiveFails() throws IOException {
var adapter = moshi.adapter(AbsentValues.class);
try {
adapter.fromJson("{\"s\":\"\"}");
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessageThat().isEqualTo("Required value 'i' missing at $");
}
}

@Test
public void nullPrimitiveFails() throws IOException {
var adapter = moshi.adapter(AbsentValues.class);
try {
adapter.fromJson("{\"s\":\"\",\"i\":null}");
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessageThat().isEqualTo("Expected an int but was NULL at path $.i");
}
}

@Test
public void absentObjectIsNull() throws IOException {
var adapter = moshi.adapter(AbsentValues.class);
String json = "{\"i\":5}";
AbsentValues value = new AbsentValues(null, 5);
assertThat(adapter.fromJson(json)).isEqualTo(value);
assertThat(adapter.toJson(value)).isEqualTo(json);
}

@Test
public void nullObjectIsNull() throws IOException {
var adapter = moshi.adapter(AbsentValues.class);
String json = "{\"i\":5,\"s\":null}";
AbsentValues value = new AbsentValues(null, 5);
assertThat(adapter.fromJson(json)).isEqualTo(value);
assertThat(adapter.toJson(value)).isEqualTo("{\"i\":5}");
}

public static record AbsentValues(String s, int i) {}
}
Expand Up @@ -157,6 +157,14 @@ public T fromJson(JsonReader reader) throws IOException {
} catch (InvocationTargetException e) {
throw rethrowCause(e);
} catch (Throwable e) {
// Don't throw a fatal error if it's just an absent primitive.
for (int i = 0, limit = componentBindingsArray.length; i < limit; i++) {
if (resultsArray[i] == null
&& componentBindingsArray[i].accessor.type().returnType().isPrimitive()) {
throw Util.missingProperty(
componentBindingsArray[i].componentName, componentBindingsArray[i].jsonName, reader);
}
}
throw new AssertionError(e);
}
}
Expand Down