Search code examples
javajsonsimplejson

How to extract data of my simplejson array?


I want to extract all the annotation of my JSONArray object and I found this post https://www.mkyong.com/java/json-simple-example-read-and-write-json/. The problem is that my JSONArray is a kind of "array of array":

[{"AnnotationOfzelda":
 [{"annotation":
  [{"duration":5000,"annotation":"salut","timestamp":2250.0}, 
   {"duration":5000,"annotation":"jp","timestamp":4570.0}]}, 
   {"duration":5000,"annotation":"asd","timestamp":3340.0}, 
   {"duration":5000,"annotation":"asd","timestamp":4040.0}]}]

I tried this code (from the post I linked)

 System.out.println(annotationJSON.toJSONString());

 Iterator<JSONObject> iterator = annotationJSON.iterator();
 while (iterator.hasNext()) {
  JSONObject factObj = (JSONObject) iterator.next();
  String annotation = (String) factObj.get("annotation");
  System.out.println(annotation);
 }

And the result is "null" and I think it's because I need to go in the array "annotation" and at the moment I'm only in "AnnotationOfzelda"


Solution

  • Try this you can use it for specific value in the JSON (annotation:"asd") or for full JSON:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.io.IOException;
    import java.util.Iterator;
    
    public class Sol {
        public static void main(String[] args) {
            String data = "[{\"AnnotationOfzelda\":\n" +
                    " [{\"annotation\":\n" +
                    "  [{\"duration\":5000,\"annotation\":\"salut\",\"timestamp\":2250.0}, \n" +
                    "   {\"duration\":5000,\"annotation\":\"jp\",\"timestamp\":4570.0}]}, \n" +
                    "   {\"duration\":5000,\"annotation\":\"asd\",\"timestamp\":3340.0}, \n" +
                    "   {\"duration\":5000,\"annotation\":\"asd\",\"timestamp\":4040.0}]}]";
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = null;
            try {
                jsonNode = objectMapper.readTree(data);
                Iterator iterator = jsonNode.iterator();
                while (iterator.hasNext()) {
                    JsonNode node = (JsonNode) iterator.next();
                    if (node.get("annotation") != null) {
                        System.out.println(node.get("annotation"));
                        continue;
                    }
                    if (node.iterator().hasNext()) {
                        iterator = node.iterator();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    Output [{"duration":5000,"annotation":"salut","timestamp":2250.0},{"duration":5000,"annotation":"jp","timestamp":4570.0}] "asd" "asd"