Home > Mobile >  jayway library | Reading a JSON from JSONPath
jayway library | Reading a JSON from JSONPath

Time:09-29

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"
    }
  1. I tried context.set method to add but it will give me all elements.
  2. 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.

CodePudding user response:

Short answer: use context.put on a new context, instead of context.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:

String sb = " { \"fruit\":\"Apple\", \"size\":\"Large\", \"price\":\"40\" }";
DocumentContext context = JsonPath.parse(sb);
String key = "fruit";
Object rawData = context.read("$."   key);
        
// create a new context containing an empty JSON object:
DocumentContext context2 = JsonPath.parse("{}");
// add your JSON to the root of the object:
context2.put("$", key, rawData);
// print the result:
System.out.println(context2.jsonString());

This outputs the following:

{"fruit":"Apple"}

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.

CodePudding user response:

You may consider another library Josson for simpler syntax.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString("{\"fruit\":\"Apple\", \"size\":\"Large\", \"price\":\"40\"}");
JsonNode node = josson.getNode("map(fruit)");
System.out.println(node.toPrettyString());

Output

{
  "fruit" : "Apple"
}
  • Related