【发布时间】:2020-03-01 14:54:07
【问题描述】:
我有一个类似的模型:
class PotholeData {
List<Coordinates> coordinates;
String location;
String image;
PotholeData({this.coordinates, this.location, this.image});
PotholeData.fromJson(Map<String, dynamic> json) {
if (json['coordinates'] != null) {
coordinates = new List<Coordinates>();
json['coordinates'].forEach((v) {
coordinates.add(new Coordinates.fromJson(v));
});
}
location = json['location'];
image = json['image'];
}
Map<String, dynamic> toJson()
{
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.coordinates != null) {
data['coordinates'] = this.coordinates.map((v) => v.toJson()).toList(); }
data['location'] = this.location;
data['image'] = this.image;
return data;
}
}
class Coordinates {
String x;
String y;
String w;
String h;
Coordinates({this.x, this.y, this.w, this.h});
Coordinates.fromJson(Map<String, dynamic> json) {
x = json['x'];
y = json['y'];
w = json['w'];
h = json['h'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['x'] = this.x;
data['y'] = this.y;
data['w'] = this.w;
data['h'] = this.h;
return data;
}
}
我正在尝试将这些数据放入 Firebase,我的做法是:
Map<String, dynamic> potholeData = PotholeData(
coordinates: sampleCoordinates,
image: "File name",
location: "Live Location").toJson();
obj.addData(potholeData).catchError((e) {
print(e);
});
}
其中 sampleCoordinates 是类型坐标的列表。但我没有得到其中应该包含什么形式的数据。我尝试在其中使用硬编码数据,但每次我输入任何内容时都会弹出一个错误,指出无法将 List/Map/String/int 类型的元素分配给列表类型 Coordinates。
示例 JSON 数据如下所示:
{
"coordinates": [
{
"x": "x_coor",
"y": "y_coor",
"w": "width",
"h": "heigth"
},
{
"x": "x_coor",
"y": "y_coor",
"w": "width",
"h": "heigth"
}
],
"location": "location",
"image": "image"
}
我需要帮助来了解 sampleCoordinates 中应该包含哪些类型的数据。它应该是 Map/List/String/int 吗? sampleCoordinates 是硬编码的,供您参考。
我曾尝试放置一些如下所示的数据,但没有一个有效。从技术上讲,第一个应该有效。 尝试了以下方法:
List<Coordinates> sampleCoordinates = [{
"x": "x_coor",
"y": "y_coor",
"w": "width",
"h": "heigth"
},
{
"x": "x_coor",
"y": "y_coor",
"w": "width",
"h": "heigth"
}];
OR
List<Coordinates> sampleCoordinates = [123,1234];
OR
List<Coordinates> sampleCoordinates = ["asb","adgad"];
【问题讨论】:
-
@Kahou 不,它没有。这个问题纯粹是针对 SharedPrefs 的,它没有展示如何创建特定类型的嵌套 JSON 数据!