借鉴原文章
https://www.cnblogs.com/sirui888/p/4749991.html
直接用对象转json,会出现对象名在{}前面,然后我结合了自己的业务逻辑,选取了部分属性,拼接,和{
public String findByCid(@RequestParam("cid")Integer cid,@RequestParam("wx_userid")Integer wx_userid) throws Exception{
StringBuilder json = new StringBuilder();
json.append("[");
List<Record> records = recordService.findByCid(wx_userid,cid);
if(records != null && records.size() >0){
for(Record record:records ){
json.append("{");
json.append(record.getId());
json.append(",");
json.append(record.getTitle());
json.append(",");
json.append(record.getContent());
json.append(",");
json.append(record.getCreateTimeStr());
json.append("},");
}
json.setCharAt(json.length() - 1, ']');
}else{
json.append("]");
}
System.out.println(json);
System.out.println(json);
return json.toString();
}
结果是这样
但是我又发现,小程序端的json数据,需要有键值对的,所以我又改进了一下,给字符串加上了引号
for(Record record:records ){
json.append("{id:");
json.append(record.getId());
json.append(",title:\"");
json.append(record.getTitle());
json.append("\",content:\"");
json.append(record.getContent());
json.append("\",createTime:\"");
json.append(record.getCreateTimeStr());
json.append("\"},");
}
结果打印出来的是这样:
[{id:17,title:"asdfasdf",content:"sfasdf",createTime:"2020-11-29 13:57:52"},
{id:18,title:"112",content:"123",createTime:"2020-11-29 13:59:36"},
{id:19,title:"sdaf",content:"sadf",createTime:"2020-11-29 14:15:44"}]
但是小程序不识别这json格式,必须要标准的json格式,然后有在key值加上冒号
for(Record record:records ){
json.append("{\"id\":");
json.append(record.getId());
json.append(",\"title\":\"");
json.append(record.getTitle());
json.append("\",\"content\":\"");
json.append(record.getContent());
json.append("\",\"createTime\":\"");
json.append(record.getCreateTimeStr());
json.append("\"},");
}
微信小程序端,wxml页面也可以获取data数组
java后台打印是这组数据
[{"id":17,"title":"asdfasdf","content":"sfasdf","createTime":"2020-11-29 13:57:52"},
{"id":18,"title":"112","content":"123","createTime":"2020-11-29 13:59:36"},
{"id":19,"title":"sdaf","content":"sadf","createTime":"2020-11-29 14:15:44"}]
过几天我再尝试一下使用map集合看行不行。
版权声明:本文为qq_37135231原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。