gpt4 book ai didi

json - 我的RCP客户端未返回对象的深拷贝

转载 作者:行者123 更新时间:2023-12-03 02:57:12 25 4
gpt4 key购买 nike

我一直在使用RCP客户端来处理天气数据。

我要做的是两件事,首先我将要使用的JSON抓取到了dart文件中。另请:https://dartpad.dartlang.org/a9c1fe8ce34c608eaa28

我的server.dart页面将导入天气数据,然后执行以下操作:

import "dart:io";
import "weather_data.dart";
import "dart:convert";
import "package:rpc/rpc.dart";

find ApiServer _apiServer = new ApiServer(prettyPrint:true);
main() async {
Weather w = new Weather(WeatherJson);
TestServer ts = new TestServer(w);
_apiServer.addApi(ts);
HttpServer server = await HttperServer.bind(InternetAddress.ANY_IP_V4, 12345);
server.listen(_apiServer.httpRequestHandler);
}

class Weather{
Map weather;
Weather(this.weather){
Map get daily => weather["daily"];
}
}

@ApiClass(name:"test_server", version: 'v1', description: 'This is a test server api to ping for some quick sample data.')
class TestServer {
Weather myWeather;
TestServer(this.myWeather){

}

@ApiMethod(method:'GET', path: 'daily')
Map<String, Object> getDaily(){
return myWeather.daily;
}
}

因此,服务器正确启动,我将转到 localhost:12345/test_server/v1/daily,它将返回此代码:
{
"summary": {},
"icon": {},
"data": {}
}

这是不正确的。如果您查找JSON数据,则summary和icon都是字符串,而data是一个数组。它们也是空的,应该包含我想返回的数据。

为什么会发生这种情况?是因为我要返回 Map<String, Object>吗?我试图将其设置为: Map<String, dynamic>,但是dart编译器不喜欢它。

如何获取此数据以返回正确的数据集?

RPC的Dart网站位于: https://github.com/dart-lang/rpc
并且您可以看到在方法下,方法的返回值可以是类的实例,也可以是Future的值。像往常一样,这很有意义,因此我通过说: Map<String,Object>不够,试图将其设置为 Map

编辑:

在不使用RPC的 Dart 垫中进行此操作时,似乎可以正常工作,例如: https://dartpad.dartlang.org/3f6dc5779617ed427b75

这使我相信解析工具出了点问题,因为dartpad中的返回类型似乎允许返回 MapMap<String, Object>Map<String, dynamic>

最佳答案

https://pub.dartlang.org/packages/rpc中快速浏览了RPC软件包README之后,似乎标记为Api方法的方法(使用@ApiMethod)应该返回具有简单字段的类的实例,例如:

class ResourceMessage {
int id;
String name;
int capacity;
}

RPC软件包将采用该实例,并根据字段名称将其序列化为JSON。

从自述文件:

The MyResponse class must be a non-abstract class with an unnamed constructor taking no required parameters. The RPC backend will automatically serialize all public fields of the the MyResponse instance into JSON ...



您正在返回希望RPC操作发出的JSON的嵌套 Map表示形式,并且会猜测RPC包未按您期望的方式处理它。

回复:来自您的问题:

This leads me to believe something is wrong with the Parsing tool as it seems the return type in dartpad allows to return Map, Map, and Map.



您的示例中没有对JSON进行“解析”。您拥有的数据是一组嵌套的文字Dart MapListString,其结构与从其派生的JSON相同。它恰好看起来像JSON。

在您的示例中,您只是选择并打印数据映射的子映射( data['daily']),该子映射会打印出通过调用 String生成的 toString()-这是递归的,因此您可以获取所有嵌套映射的内容以及其中的列表。

因此,这不是“深层复制”问题,而是 toString()和RPC代码如何处理一组嵌套映射的差异。

顺便说一句: getDaily()方法的返回类型无关紧要。无论方法的声明返回类型如何,返回的只是 Map。请记住,Dart中的类型是可选的,编辑器和编译器在那里可以发现潜在的错误代码。参见 https://www.dartlang.org/docs/dart-up-and-running/ch02.html#variables

关于json - 我的RCP客户端未返回对象的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com