fromJson static method
Creates an Attributes instance from a JSON map. This is a utility method for deserialization from logs or exports.
Implementation
static Attributes fromJson(Map<String, dynamic> json) {
final attributes = <Attribute<Object>>[];
for (final entry in json.entries) {
final key = entry.key;
final value = entry.value;
if (value is String) {
attributes.add(AttributeCreate.create<String>(key, value));
} else if (value is bool) {
attributes.add(AttributeCreate.create<bool>(key, value));
} else if (value is int) {
attributes.add(AttributeCreate.create<int>(key, value));
} else if (value is double) {
attributes.add(AttributeCreate.create<double>(key, value));
} else if (value is List<String>) {
attributes.add(AttributeCreate.create<List<String>>(key, value));
} else if (value is List<bool>) {
attributes.add(AttributeCreate.create<List<bool>>(key, value));
} else if (value is List<int>) {
attributes.add(AttributeCreate.create<List<int>>(key, value));
} else if (value is List<double>) {
attributes.add(AttributeCreate.create<List<double>>(key, value));
} else if (value is List) {
// Try to convert the list to a supported type
if (value.isNotEmpty) {
if (value.every((e) => e is String)) {
attributes.add(AttributeCreate.create<List<String>>(
key, value.cast<String>()));
} else if (value.every((e) => e is bool)) {
attributes.add(
AttributeCreate.create<List<bool>>(key, value.cast<bool>()));
} else if (value.every((e) => e is int)) {
attributes
.add(AttributeCreate.create<List<int>>(key, value.cast<int>()));
} else if (value.every((e) => e is double || e is int)) {
// Convert all to double
attributes.add(AttributeCreate.create<List<double>>(
key,
value
.map((e) => e is int ? e.toDouble() : e as double)
.toList()));
} else {
OTelErrorHandling.report(ArgumentError(
'Ignoring attribute $key because the list contains unsupported types. Only String, bool, int, double lists are allowed by the OTel specification.'));
}
} else {
OTelErrorHandling.report(ArgumentError(
'Ignoring attribute $key because empty lists are not allowed by the OTel specification.'));
}
} else {
OTelErrorHandling.report(ArgumentError(
'Ignoring attribute $key because the value is not a valid attribute type. Only String, bool, int, double and Lists of those types are allowed by the OTel specification.'));
}
}
return AttributesCreate.create(attributes);
}