I am using jayway library as I have to use JSONPath Expressions.
{
"fruit":"Apple",
"size":"Large",
"price":"40"
}
Above is my json, now from this JSON suppose I want to read from a specific path. For Ex: - $.fruit So the code snippet will be like Assuming I have read the json file and and it is stored here after converting it to string.
String sb ="input json";
DocumentContext context = JsonPath.parse(sb);
Object rawData = context.read(path);
Considering this will give me String as it is definte path. I will have "Apple" stored in "sb"
Now what if I want to add this String value to a different JSON which will have only this element in it. Using jayway library classes.
{
"fruit":"Apple"
}
- I tried context.set method to add but it will give me all elements.
- Also tried context.remove method but for that I will have to specifically provide the remaining path. (if there is any negate condition like context.remove(!"$.fruit") which will remove every element aprat from fruit), I think I can still achieve but couldn't find that as well.
Short answer: use
context.puton a new context, instead ofcontext.set.Details:
If you want to create a new JSON object containing
{"fruit":"Apple"}, you can take your starting point and extend it as follows:This outputs the following:
I don't know of a path operator which means "everything except" the one thing you want to keep. If you wanted to go this way, maybe you would have to iterate the original JSON and delete each object which does not equal the data to be kept.