JsonConvert反序列化整数失败:Xamarin调用Flask-RESTful接口问题
解决Xamarin Forms调用Flask-RESTful API反序列化整数失败的问题
嘿,我之前也碰到过类似的坑,咱们一步步来排查和解决这个问题——反序列化失败几乎都是因为API返回的内容不是有效的JSON整数格式,或者Xamarin端获取到的内容不符合预期。
1. 先把Flask API的返回格式搞对
Flask自带的jsonify有点坑,如果直接传单个整数,它会生成奇怪的JSON(比如把整数当键,值设为null)。要返回纯JSON整数,得换个写法:
import json from flask import Flask, Response from flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class IntegerResource(Resource): def get(self): # 这样返回的是纯JSON格式的整数,比如直接输出123,不带引号也不是键值对 return Response(json.dumps(123), mimetype='application/json') api.add_resource(IntegerResource, '/') if __name__ == '__main__': app.run(port=50024, debug=True)
先在浏览器里访问http://localhost:50024/,确认返回的是纯数字(比如123),而不是带引号的字符串或者一堆HTML代码。
2. 在Xamarin端先看清楚拿到的是什么
别着急反序列化,先把API返回的原始内容打出来看看,这样能快速定位问题:
HttpClient client = new HttpClient(); // 划重点!Android模拟器不能用localhost,要换成10.0.2.2;iOS模拟器直接用localhost就行 var apiUrl = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:50024/" : "http://localhost:50024/"; var response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { var jsonstring = await response.Content.ReadAsStringAsync(); // 把拿到的内容打印到调试窗口,看看实际是什么 System.Diagnostics.Debug.WriteLine($"API返回的原始内容: {jsonstring}"); try { int result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jsonstring); System.Diagnostics.Debug.WriteLine($"反序列化成功啦!结果是: {result}"); // 这里写你的业务逻辑代码 } catch (Newtonsoft.Json.JsonException ex) { System.Diagnostics.Debug.WriteLine($"反序列化炸了: {ex.Message}"); // 如果拿到的是带引号的字符串(比如"123"),可以这么救一下 if (int.TryParse(jsonstring.Trim('"'), out int parsedResult)) { System.Diagnostics.Debug.WriteLine($"通过字符串解析成功: {parsedResult}"); } } } else { System.Diagnostics.Debug.WriteLine($"API请求失败,状态码: {response.StatusCode}"); var errorContent = await response.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine($"错误内容: {errorContent}"); }
3. 几个容易踩的坑要注意
- 模拟器的localhost陷阱:Android模拟器里的
localhost指的是模拟器自己,不是你的电脑,必须用10.0.2.2才能访问电脑上跑的Flask API;iOS模拟器可以直接用localhost。 - Flask返回的是字符串不是整数:如果API返回的是
"123"(带双引号),那DeserializeObject<int>肯定失败,这时候要么改Flask返回纯整数,要么用上面代码里的int.TryParse方法处理。 - API根本没跑起来:如果返回的是HTML错误页面(比如404、500),那反序列化肯定失败,先在浏览器里测一下API地址,确认返回的是预期的数字。
内容的提问来源于stack exchange,提问作者Sa Ra
相关产品推荐
相关产品推荐

