I have an object with fields a
and b
. For example, I need to add object.a+10
logic to JSON, and then pass this JSON to Java and perform an action on the object and its field a
.
I want to write, for example, like this:
{
"object" : {
"a": 1,
"b": 10
},
"operand1": "object.a",
"operand2": "10",
"operation": "+"
}
Or like this:
{
"object" : {
"a": 1,
"b": 10
},
"action": "object.a + 10",
}
Is it possible? How can this be better implemented?
2
Answers
You can use the first option and turn operation into a enum so that it can handle some operation.
Don’t forget to add appropriate exception handling etc.
Seems that you want to support both supplying directly a value as an operand and a reference to a value. The example with the reference is basically a JSONPath (well, almost).
For simple use cases you could write your own simplified implementation, but for anything more complex you should use a library. I would suggest Jayway JsonPath, it is a java implementation of the JSONPath specification.
The most important (missing part) in this example is that you write the logic to select the correct resolver based on the value. A simplified example, based on delegation may look like this:
I would also strongly suggest to rethink your json structure and pick something, which does not constrain you into using
Map<String, Object>
. Basically something, which would allow you to parse into custom object, something like this: