英文:
how to convert nested json payload into for Restassured POST call using Map?
问题
{
"@serviceName": "75MultipleService",
"inputs": [
{
"@name": "inp1",
"value": "8",
"@type": "number"
},
{
"@name": "inp2",
"value": "8",
"@type": "number"
}
]
}
你可以使用以下Java代码将嵌套的JSON数据传递为POST请求的主体:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
// 创建一个包含你的JSON数据的Map
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("@serviceName", "75MultipleService");
List<Map<String, Object>> inputs = new ArrayList<>();
Map<String, Object> input1 = new HashMap<>();
input1.put("@name", "inp1");
input1.put("value", "8");
input1.put("@type", "number");
inputs.add(input1);
Map<String, Object> input2 = new HashMap<>();
input2.put("@name", "inp2");
input2.put("value", "8");
input2.put("@type", "number");
inputs.add(input2);
requestBody.put("inputs", inputs);
// 设置HTTP头部
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 创建HTTP实体
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
RestTemplate restTemplate = new RestTemplate();
String url = "your_post_url_here";
String response = restTemplate.postForObject(url, requestEntity, String.class);
请确保替换 "your_post_url_here"
为你要发送POST请求的实际URL。这段代码会将你的JSON数据转化为HTTP请求体,并将其发送到指定的URL。
英文:
{
"@serviceName": "75MultipleService",
"inputs": [
{
"@name": "inp1",
"value": "8",
"@type": "number"
},
{
"@name": "inp2",
"value": "8",
"@type": "number"
}
]
}
I am trying this but not understating how to pass input2
Map <String, Object> map = new HashMap<> ();
map.put("@serviceName", "75MultipleService");
map.put("inputs", Arrays.asList(new HashMap<String, Object>() {{
put("@name", "inp1");
put("value", "8");
put("@type", "number");
}}));
How to pass nested json to post request?
答案1
得分: 0
如何传递 input2
这只是另一个 Map,你可以这样做。
Map<String, Object> input1 = Map.of("@name", "inp1", "value", "8", "@type", "number");
Map<String, Object> input2 = Map.of("@name", "inp2", "value", "8", "@type", "number");
Map<String, Object> payload = Map.of("@serviceName", "75MultipleService", "inputs", List.of(input1, input2));
英文:
> how to pass input2
It's just another Map, you can do like this.
Map<String, Object> input1 = Map.of("@name", "inp1", "value", "8", "@type", "number");
Map<String, Object> input2 = Map.of("@name", "inp2", "value", "8", "@type", "number");
Map<String, Object> payload = Map.of("@serviceName", "75MultipleService", "inputs", List.of(input1, input2));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论