如何使用 postforobject 方法将 ArrayList/Set 转换为 JSON 和 post 数据?
How can I convert ArrayList/Set to JSON and post data using postforobject method?
我已经设置了包含字符串 ["a" , "b" , "c"]
,我想要 POST
json 数据(逗号分隔和一个字符串)
这里是
JSON
{"view" : "a,b,c",
"fruits" : "apple"}
使用 Resttemplate postForObject 方法结束?我使用了 GSON
但这在我的项目中不起作用。还有其他选择吗?
这是我的代码
private run(set<data> datas) {
Set<string> stack = new hashset<>();
iterator<data> itr = datas.iterator();
while (itr.hasnext()) {
data macro = itr.next();
if (//some condition) {
stack.add(macro);
}
}
}
}
Resttemplate.getmessageconverters().add(stringconvertor);
String result = resttemplate.postforobject(endpoint, request, String.class);
}
如果数据采用特定的 class 格式,您可以使用 Spring Boot.但是看你的例子,好像你想实现一次性 JSON 对象响应。
import org.json.simple.JSONObject;
public static void run(set<data> datas, string endpoint){
// build your 'stack' set
String joined = String.join(",", stack);
JSONObject obj=new JSONObject();
obj.put("view",joined);
obj.put("fruits","apple");
//return the jsonObject as the response to your entrypoint using your method
}
如果您在 Spring 引导中使用 @ResponseBody 注释,您也可以尝试以下操作,将响应主体转换为适当的 (JSON) 格式。
HashMap<String, String> map = new HashMap<>();
map.put("view", joined);
map.put("fruits", "apple");
return map;
我已经设置了包含字符串 ["a" , "b" , "c"]
,我想要 POST
json 数据(逗号分隔和一个字符串)
这里是
JSON
{"view" : "a,b,c",
"fruits" : "apple"}
使用 Resttemplate postForObject 方法结束?我使用了 GSON
但这在我的项目中不起作用。还有其他选择吗?
这是我的代码
private run(set<data> datas) {
Set<string> stack = new hashset<>();
iterator<data> itr = datas.iterator();
while (itr.hasnext()) {
data macro = itr.next();
if (//some condition) {
stack.add(macro);
}
}
}
}
Resttemplate.getmessageconverters().add(stringconvertor);
String result = resttemplate.postforobject(endpoint, request, String.class);
}
如果数据采用特定的 class 格式,您可以使用 Spring Boot.但是看你的例子,好像你想实现一次性 JSON 对象响应。
import org.json.simple.JSONObject;
public static void run(set<data> datas, string endpoint){
// build your 'stack' set
String joined = String.join(",", stack);
JSONObject obj=new JSONObject();
obj.put("view",joined);
obj.put("fruits","apple");
//return the jsonObject as the response to your entrypoint using your method
}
如果您在 Spring 引导中使用 @ResponseBody 注释,您也可以尝试以下操作,将响应主体转换为适当的 (JSON) 格式。
HashMap<String, String> map = new HashMap<>();
map.put("view", joined);
map.put("fruits", "apple");
return map;