JSON 字符串包装在另一个 JSON 对象中

问题描述 投票:0回答:1

以下是我的短信课程

public class SMS implements Notification {

    private static final Logger LOG = LogManager.getLogger(SMS.class);
    private static final Properties PROP = PropertyReader.loadProperties(PropertyFile.OTP);
    private static final String SMS_API_URL_PROP = "otp.sms.common.api.url";
    private static final String SMS_PROVIDER = "otp.sms.provider.name";

    private static final String MOBILE_NUMBER_FIELD = "MobileNumber";
    private static final String MESSAGE_FIELD = "Message";
    private static final String PROVIDER_FIELD = "Provider";
    private static final String CALLER_URL_FIELD = "CallerUrl";
    private static final String PROVIDER_VALUE = PROP.getProperty(SMS_PROVIDER);
    private static final String REQUEST_DATA_FIELD = "RequestData";

    private String recipient;
    private String smsTemplate;
    private String[] smsParams;
    private String callerUrl;
    private String requestId;
    private String channel;

    public SMS(String recipient, String smsTemplate, String[] smsParams, String callerUrl, String requestId, String channel) {
        this.recipient = recipient;
        this.smsTemplate = smsTemplate;
        this.smsParams = smsParams;
        this.callerUrl = callerUrl;
        this.requestId = requestId;
        this.channel = channel;
    }

    public SMS(String recipient, String smsTemplate, String... smsParams) {
        this.recipient = recipient;
        this.smsTemplate = smsTemplate;
        this.smsParams = smsParams;
    }

//    public SMS(String recipient, String smsTemplate, String callerUrl, String requestId, String channel,
//            String... smsParams) {
//        this.recipient = recipient;
//        this.smsTemplate = smsTemplate;
//        this.smsParams = smsParams;
//        this.callerUrl = callerUrl;
//        this.requestId = requestId;
//        this.channel = channel;
//    }

    @Override
    public boolean send() throws IllegalNotificationArgumentException {
        String smsText = String.format(this.smsTemplate, (Object[]) this.smsParams);
        return sendSMS(this.recipient, smsText, this.callerUrl, this.requestId, this.channel);
    }

    /**
     * Sends an SMS to this mobile number
     *
     * @param recipient
     * @param text
     * @return
     * @throws IllegalNotificationArgumentException
     */
    private boolean sendSMS(String recipient, String text, String callerUrl, String requestId, String channel)
            throws IllegalNotificationArgumentException {
        LOG.debug("Sending SMS notification to: " + recipient);
        System.out.println("SMS DATA : "+ recipient + " "  +text + " " +callerUrl + " " + requestId + " " +channel + " ");

        try {
            if (StringUtils.isNotBlank(recipient) && StringUtils.isNotBlank(text)) {

                submitShortMessage(recipient, text, callerUrl, requestId, channel);
                return true;
            } else {
                LOG.warn("Throwing IllegalNotificationArgumentException");
                throw new IllegalNotificationArgumentException(
                        "Illegal Notification Arguments in sendSMS()");
            }
        } catch (IOException | UserStoreException e) {
            LOG.error("Failed to invoke SMS API: " + e.getMessage());
        }
        return false;
    }

    /**
     * submitShortMessage
     *
     * @param mobile
     * @param text
     * @throws IOException
     */
    private void submitShortMessage(String mobile, String text, String callerUrl, String requestId, String channel)
            throws IOException, UserStoreException {
        // LOG.info("mobile : " + mobile + ", text : " + text);
        // CloseableHttpClient apacheHttpClient =
        // HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        CloseableHttpClient apacheHttpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .build();

        try {
            String smsApiUrl = PROP.getProperty(SMS_API_URL_PROP);
            if(callerUrl == null){
                System.out.println("CALLER URL NULLL");
                callerUrl = "sms-tigo-trust-lk";
            }
            JsonNode sendOtpJson = getSendOTPJson(mobile, text, callerUrl);
            LOG.debug("SMS API url: " + smsApiUrl);
            LOG.debug("Send sms json: " + sendOtpJson);
            HttpPost httpPost = new HttpPost(smsApiUrl);

            // Add headers
            httpPost.setHeader("Channel", channel);
            httpPost.setHeader("RequestId", requestId);
            httpPost.setHeader("Content-Type", "application/json");

            // Set request body
            StringEntity entity = new StringEntity(sendOtpJson.toString());
            httpPost.setEntity(entity);
            System.out.println("HTTP POSTTT :"+ httpPost);

           CloseableHttpResponse response = HttpClient.post(apacheHttpClient, httpPost);
            System.out.println("RESPONSEEEE :"+ response);
            //CloseableHttpResponse response = apacheHttpClient.execute(httpPost);

            String stringResponseEntity = null;
            if (response != null) {
                HttpEntity responseEntity = response.getEntity();
                stringResponseEntity = EntityUtils.toString(responseEntity);
            }
            System.out.println("STRING RESPONSE ENTITY :"+ stringResponseEntity);
            try {
                if (response != null
                        && response.getStatusLine().getStatusCode() == APIConstant.SUCCESS_STATUS) {
                    LOG.debug("Message submitted: " + stringResponseEntity);
                    LOG.info("SMS notification successfully sent to: " + mobile);
                } else {
                    throw new IOException(stringResponseEntity);
                }

            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } finally {
            apacheHttpClient.close();
        }
    }

    /**
     * @param recipient
     * @param message
     * @return JsonNode - POST otp send JSON
     */
    private JsonNode getSendOTPJson(String recipient, String message, String callerUrl) {

        ObjectMapper mapper = new ObjectMapper(); // creates mapper object
        JsonNode rootNode = mapper.createObjectNode(); // creates root node
        JsonNode requestDataNode = mapper.createObjectNode(); // creates root node

        ((ObjectNode) requestDataNode).put(MOBILE_NUMBER_FIELD, recipient);
        ((ObjectNode) requestDataNode).put(MESSAGE_FIELD, message);
        ((ObjectNode) requestDataNode).put(PROVIDER_FIELD, PROVIDER_VALUE);
        ((ObjectNode) requestDataNode).put(CALLER_URL_FIELD, callerUrl);

        // add OTP request fields
        ((ObjectNode) rootNode).put(REQUEST_DATA_FIELD, requestDataNode);

        return rootNode;

    }

}

我需要的是将以下格式的手机号码、呼叫者 URL、消息和提供商值发送到使用 wso2 EI 创建的 api。

{
    "RequestData": {
        "MobileNumber": "255756583454",
        "Message": "Ndugu mteja sasa unaweza jiunga na SIMbanking kwa kupiga *150*03#. Namba yako ya siri ni 4145",
        "Provider": "INFOBIP",
        "CallerUrl": null
    }
}

当我在 api 中记录请求正文时,我收到以下请求 ``{“text”:“{“RequestData”:{“MobileNumber”:“255756583444”,“Message”:“Ndugu mteja,namba yako ya SimBanking imebadilishwa kutoka 255756583444 kwenda 255756583854。Kwa maelezo zaidi Piga 0755197700。”,“提供商":"INFOBIP","CallerUrl":"sms-tigo-trust-lk"}}"}

 
为什么它被包裹在名为“text”的键中?如何修复它?请帮忙。

java json wso2-identity-server objectmapper jsonnode
1个回答
0
投票

您的请求正文被包含在名为“text”的键中的原因可能是由于您将 JSON 对象转换为字符串时它的序列化方式。

你能试试这个吗?

// Set request body without unnecessary wrapping
StringEntity entity = new StringEntity(sendOtpJson.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
© www.soinside.com 2019 - 2024. All rights reserved.