javaelixir-jason

How to remove this Jason response(timestamp, status, error, path)? I just want to get object data


{ "courseId": 23, "courseName": "science", "courseCode": "SC100", "courseDescription": "linear algebra", "courseDuration": "6 m", "createdDate": 1630438611000, "updatedDate": null, "removeImages": [] }{ "timestamp": 1630614081354, "status": 200, "error": "OK", "path": "/api/editcourse/23" }


Solution

  • I would use Jackson Project for that task.

    Alternative 1

    Since you have 2 values in the same Json and you want only the first, you can use readTree(String) method from ObjectMapper class. It will skip the second value.

    ObjectMapper mapper = new ObjectMapper();
    
    JsonNode jsonNode = mapper.readTree(jsonResponse);
    
    System.out.println(jsonNode.toPrettyString());
    

    Output:

    {
      "courseId" : 23,
      "courseName" : "science",
      "courseCode" : "SC100",
      "courseDescription" : "linear algebra",
      "courseDuration" : "6 m",
      "createdDate" : 1630438611000,
      "updatedDate" : null,
      "removeImages" : [ ]
    }
    

    Alternative 2

    Using method readValues(JsonParser, Class<T>) you can read all values an iterate selecting only the ones you need.

    ObjectMapper mapper = new ObjectMapper();
    
    Iterator<?> iterator = mapper.readValues(new JsonFactory().createParser(jsonResponse), Map.class);
    
    Object object = iterator.next();
    
    System.out.println(object);
    

    Output:

    {courseId=23, courseName=science, courseCode=SC100, courseDescription=linear algebra, courseDuration=6 m, createdDate=1630438611000, updatedDate=null, removeImages=[]}