Returns a JSON serializable dict representation of this object. Parameters ----------- casing: :class:`Casing` The casing to use for key values. Default is :attr:`Casing.CAMEL` for compatibility purposes. include_default_values: :clas
(
self, casing: Casing = Casing.CAMEL, include_default_values: bool = False
)
| 1391 | return cls().parse(data) |
| 1392 | |
| 1393 | def to_dict( |
| 1394 | self, casing: Casing = Casing.CAMEL, include_default_values: bool = False |
| 1395 | ) -> Dict[str, Any]: |
| 1396 | """ |
| 1397 | Returns a JSON serializable dict representation of this object. |
| 1398 | |
| 1399 | Parameters |
| 1400 | ----------- |
| 1401 | casing: :class:`Casing` |
| 1402 | The casing to use for key values. Default is :attr:`Casing.CAMEL` for |
| 1403 | compatibility purposes. |
| 1404 | include_default_values: :class:`bool` |
| 1405 | If ``True`` will include the default values of fields. Default is ``False``. |
| 1406 | E.g. an ``int32`` field will be included with a value of ``0`` if this is |
| 1407 | set to ``True``, otherwise this would be ignored. |
| 1408 | |
| 1409 | Returns |
| 1410 | -------- |
| 1411 | Dict[:class:`str`, Any] |
| 1412 | The JSON serializable dict representation of this object. |
| 1413 | """ |
| 1414 | output: Dict[str, Any] = {} |
| 1415 | field_types = self._type_hints() |
| 1416 | defaults = self._betterproto.default_gen |
| 1417 | for field_name, meta in self._betterproto.meta_by_field_name.items(): |
| 1418 | field_is_repeated = defaults[field_name] is list |
| 1419 | try: |
| 1420 | value = getattr(self, field_name) |
| 1421 | except AttributeError: |
| 1422 | value = self._get_field_default(field_name) |
| 1423 | cased_name = casing(field_name).rstrip("_") # type: ignore |
| 1424 | if meta.proto_type == TYPE_MESSAGE: |
| 1425 | if isinstance(value, datetime): |
| 1426 | if ( |
| 1427 | value != DATETIME_ZERO |
| 1428 | or include_default_values |
| 1429 | or self._include_default_value_for_oneof( |
| 1430 | field_name=field_name, meta=meta |
| 1431 | ) |
| 1432 | ): |
| 1433 | output[cased_name] = _Timestamp.timestamp_to_json(value) |
| 1434 | elif isinstance(value, timedelta): |
| 1435 | if ( |
| 1436 | value != timedelta(0) |
| 1437 | or include_default_values |
| 1438 | or self._include_default_value_for_oneof( |
| 1439 | field_name=field_name, meta=meta |
| 1440 | ) |
| 1441 | ): |
| 1442 | output[cased_name] = _Duration.delta_to_json(value) |
| 1443 | elif meta.wraps: |
| 1444 | if value is not None or include_default_values: |
| 1445 | output[cased_name] = value |
| 1446 | elif field_is_repeated: |
| 1447 | # Convert each item. |
| 1448 | cls = self._betterproto.cls_by_field[field_name] |
| 1449 | if cls == datetime: |
| 1450 | value = [_Timestamp.timestamp_to_json(i) for i in value] |