Skip to content

Commit

Permalink
jsonschema support array type, for issue #2931
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Sep 15, 2024
1 parent 093cd5c commit 3ed22a9
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -2157,4 +2157,9 @@ public static JSONObject from(Object obj) {
public static JSONObject from(Object obj, JSONWriter.Feature... writeFeatures) {
return (JSONObject) JSON.toJSON(obj, writeFeatures);
}

public boolean isArray(Object key) {
Object object = super.get(key);
return object instanceof JSONArray || object != null && object.getClass().isArray();
}
}
4 changes: 4 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/schema/AnyOf.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,8 @@ public ValidateResult validate(Object value) {
}
return FAIL_ANY_OF;
}

public JSONObject toJSONObject() {
return JSONObject.of("anyOf", this.items);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,15 @@ static JSONSchema of(java.lang.reflect.Type type, JSONSchema root) {

@JSONCreator
public static JSONSchema of(JSONObject input, JSONSchema parent) {
if (input.size() == 1 && input.isArray("type")) {
JSONArray types = input.getJSONArray("type");
JSONSchema[] items = new JSONSchema[types.size()];
for (int i = 0; i < types.size(); i++) {
items[i] = JSONSchema.of(JSONObject.of("type", types.get(i)));
}
return new AnyOf(items);
}

Type type = Type.of(
input.getString("type")
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.alibaba.fastjson2.issues_2900;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.schema.JSONSchema;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class Issue2931 {
@Test
public void test() {
JSONObject object = JSON.parseObject("{\"type\":\"object\",\"properties\":{\"longitude\":{\"type\":[\"string\", \"number\"]},\"latitude\":{\"type\":\"number\",\"minimum\":-90,\"maximum\":90}},\"required\":[\"longitude\",\"latitude\"]}");
System.out.println(object);
JSONSchema schema = JSONSchema.of(object);
assertTrue(schema.isValid(
JSONObject.of("longitude", "123.45", "latitude", 21.31)
));
assertFalse(schema.isValid(
JSONObject.of("longitude", false, "latitude", 21.31)
));
}
}

0 comments on commit 3ed22a9

Please sign in to comment.