Skip to content

Commit

Permalink
[json-core] Fix reading NULL value in a Map or List (#318)
Browse files Browse the repository at this point in the history
  • Loading branch information
rbygrave authored Dec 16, 2024
1 parent c5780b9 commit a7c9e9a
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ void nullJson() {
assertThat(asJson).isEqualTo("");
}

@Test
void nullInMap() {
Object val = objectType.fromJson("{\"a\":1,\"b\":null,\"c\":3}");
assertThat(val).isInstanceOf(Map.class);

String asJson = objectType.toJson(null);
assertThat(asJson).isEqualTo("");
}

@Test
void nullInList() {
Object val = objectType.fromJson("[1,null,3]");
assertThat(val).isInstanceOf(List.class);

String asJson = objectType.toJson(val);
assertThat(asJson).isEqualTo("[1,3]");
}

@Test
void booleanTrue() {
String asJson = objectType.toJson(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public Object fromJson(JsonReader reader) {
case BOOLEAN:
return booleanAdapter.fromJson(reader);
case NULL:
reader.isNullValue();
return null;
default:
throw new IllegalStateException("Expected a value but was " + reader.currentToken() + " at path " + reader.location());
Expand Down
26 changes: 26 additions & 0 deletions json-core/src/test/java/io/avaje/json/simple/SimpleMapperTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,32 @@ void mapToJsonFromJson() {
assertThat(mapFromJson2).isEqualTo(mapFromJson);
}

@Test
void nullDirectly() {
var mapFromJson = simpleMapper.fromJson("null");
assertThat(mapFromJson).isNull();
}

@Test
void mapWithNull() {
Map<String, Object> mapFromJson = simpleMapper.fromJsonObject("{\"one\":1,\"two\":null,\"three\":3}");

assertThat(mapFromJson).containsKeys("one", "two", "three");
assertThat(mapFromJson.toString()).isEqualTo("{one=1, two=null, three=3}");

assertThat(simpleMapper.toJson(mapFromJson)).isEqualTo("{\"one\":1,\"three\":3}");
}

@Test
void listWithNull() {
List<Object> listFromJson = simpleMapper.fromJsonArray("[1,null,3]");

assertThat(listFromJson).hasSize(3);
assertThat(listFromJson.get(1)).isNull();

assertThat(simpleMapper.toJson(listFromJson)).isEqualTo("[1,3]");
}

@Test
void arrayToJsonFromJson() {

Expand Down

0 comments on commit a7c9e9a

Please sign in to comment.