如何在Dart中创建特定类型的嵌套JSON数据



我有一个类似的模型

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"];

带有JSON转换的用户类:JSON和序列化

class User {
String name;
int age;
User father;
User({
this.name,
this.age,
this.father,
});
factory User.fromJson(String str) => User.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory User.fromMap(Map<String, dynamic> json) => User(
name: json["name"],
age: json["age"],
father: json["father"] == null ? null : User.fromMap(json["father"]),
);
Map<String, dynamic> toMap() => {
"name": name,
"age": age,
"father": father == null ? null : father.toMap(),
};
}

所以,我在尝试许多事情时找到了答案。sampleCoordinates应具有:

List<Coordinates> sampleCoordinates = [
Coordinates(h: '24',w: '3455', x: '34', y: '345'), 
Coordinates(h: '24',w: '3455', x: '34', y: '345')
];

这符合我的目的。

最新更新