Closed glassfishrobot closed 7 years ago
Reported by salyh
kchung said: I've actually implemented a Visitor for JSON. It is similar to what's proposed here. The main differences are:
For future reference, here's what I have
**Visitor.java**package javax.json;
import java.util.Map;
public class Visitor {
public void visit(String key, JsonObject obj) {
visit(obj);
}
public void visit(String key, JsonArray array) {
visit(array);
}
public void visit(String key, String string) {
}
public void visit(String key, JsonNumber number) {
}
public void visit(String key, boolean test) {
}
public void visit(String key) {
}
public void visit(int i, JsonObject obj) {
visit(obj);
}
public void visit(int i, JsonArray array) {
visit(array);
}
public void visit(int i, String string) {
}
public void visit(int i, JsonNumber number) {
}
public void visit(int i, boolean test) {
}
public void visit(int i) {
}
public void visit(JsonObject object) {
for (Map.Entry<String, JsonValue> entry: object.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
switch (value.getValueType()) {
case OBJECT:
visit(key, (JsonObject)value);
break;
case ARRAY:
visit(key, (JsonArray)value);
break;
case NUMBER:
visit(key, object.getJsonNumber(key));
break;
case TRUE:
case FALSE:
visit(key, object.getBoolean(key));
break;
case STRING:
visit(key, object.getString(key));
break;
case NULL:
visit(key);
break;
}
}
}
public void visit(JsonArray array) {
for (int i = 0; i < array.size(); i++) {
switch (array.get(i).getValueType()) {
case OBJECT:
visit(i, array.getJsonObject(i));
break;
case ARRAY:
visit(i, array.getJsonArray(i));
break;
case NUMBER:
visit(i, array.getJsonNumber(i));
break;
case TRUE:
case FALSE:
visit(i, array.getBoolean(i));
break;
case STRING:
visit(i, array.getString(i));
break;
case NULL:
visit(i);
break;
}
}
}
}
kchung said: However, I don't think visitors are useful. They are most useful in cases where context is not needed, like output the words in a dictionary, or compute the average age of all people. It becomes awkward when context is needed, like computing the average age of males who live in California. I have yet to come with an example where the use of visitors is compelling.
I think it would be more useful to look into using JDK's stream operations for JSON queries.
salyh said: Do we want to discuss JDK's streams within JSR 374?
kchung said: Yes, we'll look into applying JDK's streams on JSON objects. I'll open another jira to discuss it.
This issue was imported from java.net JIRA JSON_PROCESSING_SPEC-64
Marked as won't fix on Tuesday, March 7th 2017, 9:07:29 am
Implement visitor pattern for easier and more convenient JSON traversal/introspection
Here is a first sketch:
New method for JsonValue to make it visitable
Give the json constants a type
And finally the visitor interface