具有多个子节点的okHTTP POST请求正文

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

我正在使用运营商提供的收费API,并且以下JSON格式必须与API调用一起传递。我正在使用okHTTP库。

String telNum = "+941234567";

String pbody = "{\"amountTransaction\": {\"clientCorrelator\": \"7659\",\"endUserId\": \"tel:"+telNum+"\",\"paymentAmount\": {\"chargingInformation\": {\"amount\": 1,\"currency\": \"LKR\",\"description\": \"Test Charge\"},\"chargingMetaData\": {\"onBehalfOf\": \"IdeaBiz Test\",\"purchaseCategoryCode\": \"Service\",\"channel\": \"WAP\",\"taxAmount\": \"0\",\"serviceID\": \"theserviceid\"}},\"referenceCode\": \"REF-12345\",\"transactionOperationStatus\": \"Charged\"}}";```

以下是JSON格式的方式。

{
    "amountTransaction": {
        "clientCorrelator": "54321",
        "endUserId": "tel:+94761234567",
        "paymentAmount": {
            "chargingInformation": {
                "amount": 1,
                "currency": "LKR",
                "description": "Test Charge"
            },
            "chargingMetaData": {
                "onBehalfOf": "IdeaBiz Test",
                "purchaseCategoryCode": "Service",
                "channel": "WAP",
                "taxAmount": "0",
                "serviceID": "null"
            }  
        },
        "referenceCode": "REF-12345",
        "transactionOperationStatus": "Charged"
    }
}

我收到错误400错误的请求

java json okhttp
3个回答
0
投票

尝试此操作将根据您的身体要求格式化

 try {
        JSONObject jsonObject = new JSONObject(pbody);
        pbody=jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }

0
投票

OkHTTP需要RequestBodyPOST对象,所以尝试这个:

RequestBody body = RequestBody.create(MediaType.APPLICATION_JSON, pbody);
Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

0
投票

您可以使用ObjectMapperString转换为Map

ObjectMapper objectMapper = new ObjectMapper();       // package: com.fasterxml.jackson.databind
Map body = objectMapper.readValue(pbody, Map.class);  // you need to handle IOException

现在尝试将此Map而不是String作为主体传递给API。我希望它能解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.