Home > Net >  Retrieve value from returned JSON object in Java
Retrieve value from returned JSON object in Java

Time:09-16

I am a receiving a JSON object and I need to save the values to my DB. But I'm having an issue figuring out how to retrieve the particular values in the JSON object.

In this case, I want to retrieve the values of 'originationNumber' and 'messageBody'

The response object -

{"originationNumber":"***","destinationNumber":"***","messageKeyword":"KEYWORD_***","messageBody":"Answer ","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0","inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"}

Method to receive message -

public String getReceivedMessages(Messaging receivedMessage) {

    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
    AmazonSQS sqsClient = AmazonSQSClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
            .withRegion(String.valueOf(awsRegion)).build();

    StringBuilder sb = new StringBuilder();
    String queueUrl = "https://sqs.us-east-1.amazonaws.com/1234567/GetReceivedMessages";
    List<Message> messages = sqsClient.receiveMessage(new ReceiveMessageRequest(queueUrl)
            .withMaxNumberOfMessages(1).withWaitTimeSeconds(20)).getMessages();
    for (Message message : messages) {
        sb.append(message.getBody());
        sqsClient.deleteMessage(queueUrl, message.getReceiptHandle());
    }

    // Save messages to DB
    String userId = connectionRequestRepository.getUserId();
    Date date = new Date();
    Timestamp now = new Timestamp(date.getTime());

    receivedMessage.setUserId(userId);
    receivedMessage.setOriginationNumber("");
    receivedMessage.setDestinationNumber("***");
    receivedMessage.setMessageBody("");
    receivedMessage.setMessageType("RECEIVED");
    receivedMessage.setCreatedAt(now);
    messagingRepository.save(receivedMessage);

    System.out.println(sb); <--- Prints response object to console
    return sb.toString();
}

CodePudding user response:

where ur json like

     {"originationNumber":"***",
    "destinationNumber":"***",
    "messageKeyword":"KEYWORD_***",
    "messageBody":"Answer","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0",
    "inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"
    }

it like

"key":Value

i think ur code will be like

receivedMessage.setUserId(userId);
receivedMessage.setOriginationNumber("originationNumber");
receivedMessage.setDestinationNumber("destinationNumber");
receivedMessage.setMessageBody("messageBody");
receivedMessage.setMessageType("RECEIVED");
receivedMessage.setCreatedAt(now);
messagingRepository.save(receivedMessage);

CodePudding user response:

You can use jackson library for that.

Solution 1: You can use ObjectMapper as below:

Message Class to map JSON to Java Object:

public class Message {
 private String originationNumber;
 private String messageBody;

 // public getter and setters methods

}

Create Object From JSON String:

Message message = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
   message = objectMapper.readValue(payload, Message.class);
} catch (JsonProcessingException e) {
   // Log Or do some action as per need
}

Here message will have those values. DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES is used here to skip exception as there are other fields also in JSON and not present in Java Class (as we don't need them).

Solution 2: Alternatively you can use JsonNode from same Jackson library and read nodes one by one as below:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}");

String originationNumber = actualObj.get("originationNumber");
String messageBody = actualObj.get("messageBody");

In this approach you won't need to create Message class.

CodePudding user response:

You can convert the json string into a json object https://www.javatpoint.com/how-to-convert-string-to-json-object-in-java

String string = "{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}";  
JSONObject json = new JSONObject(string);  
System.out.println(json.toString());  
String destinationNumber = json.getString("destinationNumber");  
System.out.println(destinationNumber);
  • Related