Reputation: 19
I'm sending data over ble and have compacted the json strings. The json contains three arrays.
{"b":false,"l":261,"a":["0.5","1.8","2.9","1.0"]}
I have a model class of Notify. I need to create a model class for "a" that assigns a predefined key to each of the values in the list but I am not sure of the best way. The values always come in a specific order.
class Notify{
bool b;
int l;
List<String> a;
Notify({this.b, this.a, this.d, this.p});
Notify.fromJson(Map<String, dynamic> json) {
b = json['b'];
l = json['l'];
a = json['a'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['b'] = this.b;
data['l'] = this.l;
data['a'] = this.a;
return data;
}
}
I get lost in the steps. In this class I think I need to:
class A {
double a0;
double a1;
double a2;
double a3;
double a4;
double a5;
double a6;
double a7;
A a;
A({this.a0, this.a1, this.a2, this.a3, this.a4, this.a5, this.a6, this.a7});
A.fromJson(List<double> json){
// Do bring it in as a list?
List<double> angleValuesList = List<double>.from(json);
List<String> angleKeysList = ['a0', 'a1', 'a2', 'a3'];
Map<String, double> angleMap = Map.fromIterables(angleKeysList, angleValuesList);
// Then I map the first four values to a0-a3
//now lost..... how do I get close to items 3-5?
}
}
I'm hoping my map looks like this so I can create an object from it and drop it in a stream. I receive this packet every 16 milliseconds:
{"b":false,"l":261,"a":["a0": "0.5", "a1":"1.8", "a2":"2.9", "a3":"1.0", "a4": "-0.5", "a5":"-1.8", "a6":"-2.9", "a7":"-1.0"]}
Thanks for taking the time to read through this!
Upvotes: 0
Views: 105
Reputation: 3305
if you parse this {"b":false,"l":261,"a":["0.5","1.8","2.9","1.0"]}
using json.decode(data)
like this you will end up having this
data = {"b":false,"l":261,"a":["0.5","1.8","2.9","1.0"]}
steps
Map<String,dynamic> map = json.decode(data);
//as you know the data you have provided
bool b = map['b'] as bool;
int l = map['l'] as int;
//as the list is of type string ["2.2","3.1"]
List<String> a = List.castFrom(map['a']);//or map['a'] as Map<String>
//if the list could have been of type double [2.2,3.1,4.2]
List<double> a = List.castFrom(map['a']);//or map['a'] as Map<double>
Upvotes: 1