【最详细的】微信小程序与java后台交互
唉,怎么说呢,本来这么简单的问题感觉应该上网随便找篇博客就解决了,就是一个转json的事情,结果出现了好多奇奇怪怪的错误……,网上那些博客写的都不想洗,大同小异,后来终于找到了一条方便的道路来实现这个简单的功能,用Gson!
何为Gson?
GSON是Google开发的Java API,用于转换Java对象和Json对象。而JSON ( ) 是一种文本形式的数据交换格式,它比XML更轻量、比二进制容易阅读和编写,调式也更加方便。其重要性不言而喻。解析和生成的方式很多,Java中最常用的类库有:JSON-Java、Gson、Jackson、FastJson等。
POM依赖
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
Gson的基本用法
Gson提供了fromJson() 和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化。
知道了这个就一通百通了。
有关基础,参见这个博客:
微信小程序代码:
//与java后台交互 wx.request({ url: http://localhost:8080/getAllO2OStores, method: get, header: { content-type: application/json }, success: function (res) { console.log(res.data) }, fail: function (err) { } })
Java后台代码(springboot controller)
@RestController public class O2Ocontroller { @Autowired private O2OService o2OService; @RequestMapping("/getAllO2OStores") public String getAllO2OStores(){ Gson gson=new Gson(); String json=gson.toJson(o2OService.findAll()); System.out.println(json); return json; } }
用toJson,fromJson就轻松搞定了~