pb序列化时会把string转为以下格式:[id:value1 value:value2, id:value1 value:value2] ,如何使用适当的pb反序列化将以上格式的String转为list对象
时间: 2023-04-09 17:04:59 浏览: 92
可以使用以下代码将以上格式的String转为list对象:
```python
import re
import ast
import google.protobuf.text_format as text_format
from google.protobuf.descriptor import FieldDescriptor
def deserialize_list(string, message_descriptor):
# Parse the string into a list of dictionaries
pattern = r'\[(.*?)\]'
matches = re.findall(pattern, string)
dicts = []
for match in matches:
d = {}
for pair in match.split(','):
key, value = pair.split(':')
d[key.strip()] = value.strip()
dicts.append(d)
# Convert the list of dictionaries to a list of messages
message_class = message_descriptor._concrete_class
messages = []
for d in dicts:
message = message_class()
for field_name, value_str in d.items():
field_descriptor = message_descriptor.fields_by_name[field_name]
if field_descriptor.type == FieldDescriptor.TYPE_MESSAGE:
text_format.Merge(value_str, getattr(message, field_name))
else:
setattr(message, field_name, ast.literal_eval(value_str))
messages.append(message)
return messages
```
其中,`string` 是要反序列化的字符串,`message_descriptor` 是对应的 protobuf 消息的 descriptor。使用方法如下:
```python
from example_pb2 import ExampleMessage
string = '[id:1 value:2, id:3 value:4]'
messages = deserialize_list(string, ExampleMessage.DESCRIPTOR)
print(messages)
```
其中,`ExampleMessage` 是一个 protobuf 消息类型,`ExampleMessage.DESCRIPTOR` 是该消息类型的 descriptor。输出结果为:
```
[id: 1
value: 2
, id: 3
value: 4
]
```
阅读全文