0

I am calling a rest end point in Java using Unirest. The response is a JSON message which is complex and contains multiple levels inside.

I need to extract the value of a specific tag "eventDefinationId" from the response message. However, that is failing or not working. I cannot handle the JSON parsing from the response to extract the tag value

Below is the code I am using

//*Enrich Journey Event Info *//
Statement stmt_eventId = conn.createStatement();
ResultSet rs_event = stmt_eventId.executeQuery("SELECT JourneyName,definitionid FROM journeydetails");
while(rs_event.next()){
    String JourneyName_For_EventId = rs_event.getString("JourneyName");
    JourneyName_For_EventId = JourneyName_For_EventId.replaceAll(" ", "%20");
    String Event_URL = "https://xxxxxxx.rest.marketingcloudapis.com/interaction/v1/interactions?name="+JourneyName_For_EventId+"&extras=all";
    Unirest.setTimeouts(0, 0);
    HttpResponse<String> response_event = Unirest.get(Event_URL)
                                            .header("Content-Type", "application/json")
                                            .header("Authorization", Token_Auth)
                                            .asString();
    String jsonString = response_event.getBody();
    ObjectMapper mapper = new ObjectMapper();  
    com.fasterxml.jackson.databind.JsonNode actualObj = mapper.readTree(jsonString);
    String eventDefinationId = actualObj.get("eventDefinitionId").textValue();
    System.out.println(eventDefinationId);
}

Below is an example of a successful call using Postman. The image is the same API call, but using Postman instead of code.

enter image description here

As you see eventDefinationId is way below(inside metadata section) .

I want to extract it. I am getting all possible type of errors. Also this tag sometime may not be present. in that case it shouldn't error, but skip and go to next value from result set.

When I run the above program, I get null pointer exception

Exception in thread "main" java.lang.NullPointerException
at sfmc_process.ProcessJourney.UpdateJourneyDetailsTables(ProcessJourney.java:105)
at sfmc_main.AppLauncher.main(AppLauncher.java:29)

Command execution failed. org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) at org.apache.commons.exec.DefaultExecutor.executeInternal (DefaultExecutor.java:404)

Line 105 which is error is : String eventDefinitionId = actualObj.get("eventDefinitionId").textValue();

Below is the image of the code which I am using. I want to extract the eventDefinitionId from message only.

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • This looks like a typo: `eventDefinitionId` - not `eventDefinationId`. – andrewJames May 28 '23 at 14:52
  • 1
    If that does not solve your issue, try to be more specific regarding the error you are getting - not "_all possible type of errors_". Also, please [provide text as text](https://meta.stackoverflow.com/a/285557/12567365) - not as screenshots of text. You can [edit] your question as needed. – andrewJames May 28 '23 at 14:54
  • Thanks andrew , i have added the error message i get . Its null pointer error. The image contain client specfic info , thus i am not attaching the it as text and just a screenshot of message . my applogies for that. any clue what i am doing wrong or is the whole approach itself wrong? – Chandrashekhar Dautpure May 28 '23 at 15:00
  • Which line of code is `ProcessJourney.java:105`? You can see that, but we cannot. – andrewJames May 28 '23 at 15:03
  • See also [Reading value of nested key in JSON with Java (Jackson)](https://stackoverflow.com/q/29858248/12567365). – andrewJames May 28 '23 at 15:04
  • And also [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/q/218384/12567365) – andrewJames May 28 '23 at 15:05
  • 1
    @andrewJames, that would be String eventDefinitionId = actualObj.get("eventDefinitionId").textValue(); – Chandrashekhar Dautpure May 28 '23 at 15:07
  • You can [edit] the question to include this new, relevant information there (instead of in a comment). But the links to those other questions should allow you to solve this error, I believe. – andrewJames May 28 '23 at 15:09
  • mask confidential information but code should be provided as text always. – aled May 28 '23 at 15:30

1 Answers1

0

Thanks all for comments. After trying and checking different sites , i was able to come up with solution or code to resolve the problem

The approach is, i get response as Json and the i start extracting JSON objects and arrays from it. As seen below . Thanks all

//*Enrich Journey Event Info *//
    Statement stmt_eventId = conn.createStatement();
    ResultSet rs_event = stmt_eventId.executeQuery("SELECT JourneyNames FROM journeynameedited");
    //ResultSet rs_event = stmt_eventId.executeQuery("SELECT JourneyName,definitionid FROM journeydetails");
    while(rs_event.next()){
        String JourneyName_For_EventId = rs_event.getString("JourneyNames").strip().replaceAll("\\p{C}", "");
        System.out.println(JourneyName_For_EventId);
        String JourneyDefinationId = "";
        //String JourneyDefinationId = rs_event.getString("definitionid");
        String JourneyName_For_EventId_html = JourneyName_For_EventId.replaceAll(" ", "%20");
        String Event_URL = "https://xxxxxxxxxx.rest.marketingcloudapis.com/interaction/v1/interactions?name="+JourneyName_For_EventId_html+"&extras=all";
        
        Unirest.setTimeouts(0, 0);
        HttpResponse<JsonNode> response_event = Unirest.get(Event_URL)
                                                .header("Content-Type", "application/json")
                                                .header("Authorization", Token_Auth)
                                                .asJson();
        JSONObject Response_Obj_Event = response_event.getBody().getObject();
        if(Response_Obj_Event.has("items"))
        {
            JSONArray Event_Items = Response_Obj_Event.getJSONArray("items");
            for(int ii=0;ii<Event_Items.length();ii++)
            {
                JSONObject Event_Object = Event_Items.getJSONObject(ii);
                if((Event_Object.has("triggers")) && ((Event_Object.getJSONArray("triggers")!= null) && (Event_Object.getJSONArray("triggers").length()>0 )))
                {
                    JSONArray Event_Trigger_Array = Event_Object.getJSONArray("triggers");
                    if((Event_Trigger_Array.getJSONObject(0).has("metaData")) && (Event_Trigger_Array.getJSONObject(0).getJSONObject("metaData")!= null))
                    {
                        if(Event_Trigger_Array.getJSONObject(0).getJSONObject("metaData").has("eventDefinitionId"))
                        {
                            String eventDefinitionId = Event_Trigger_Array.getJSONObject(0).getJSONObject("metaData").getString("eventDefinitionId");
                            String queryString = "INSERT INTO journeyeventinfo (JourneyName,DefinationId,EventId) VALUES (\""+JourneyName_For_EventId+"\",\""+JourneyDefinationId+"\",\""+eventDefinitionId+"\");";
                            populatejourneyEventTable(conn,queryString);
                        }                            
                    }
                }
            }
        }
    }