I can't find how to serialize a message directly to JSON. It seems that you 
have to serialize it to binary first and them to JSON and the same going in 
the reverse direction.

To serialize a message to JSON I have to serialize it to binary and then 
output the binary to a string like this

  std::string serialized = startMovie.SerializeAsString(); // startMovie is 
a google::protobuf::Message
  std::string json_string;
  
  // Create a TypeResolver used to resolve protobuf message types
  google::protobuf::util::JsonOptions options;
  options.always_print_primitive_fields = true;
  std::unique_ptr<google::protobuf::util::TypeResolver> 
resolver(google::protobuf::util::NewTypeResolverForDescriptorPool(
    "type.googleapis.com", 
google::protobuf::DescriptorPool::generated_pool())); 
  
  auto status = google::protobuf::util::BinaryToJsonString(resolver.get(), 
"type.googleapis.com/movie.pbuf.Movie", serialized, &json_string, options);
   std::cout << "*******\n" << json_string << std::endl;


*But what I really want to do is*
std::string json_string = 
google::protobuf::util::MessageToJsonString(startMove); // startMovie is a 
google::protobuf::Message


And parsing from a JSON string to a Message is a two-step process also like
  // Turn JSON into serialized protobuf message
  std::string movieBin;
  google::protobuf::util::JsonToBinaryString(resolver.get(), 
"type.googleapis.com/movie.pbuf.Movie", json_string, &movieBin);  
  
  Movie startMovie2;
  startMovie2.ParseFromString(movieBin);

*But what I really want to do is*
Movie startMovie2 = 
google::protobuf::util::JsonToMessage("type.googleapis.com/movie.pbuf.Movie", 
json_string);


Maybe this exists and I just haven't found it yet?

Thanks,
Chad






-- 
You received this message because you are subscribed to the Google Groups 
"Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to protobuf+unsubscr...@googlegroups.com.
To post to this group, send email to protobuf@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Reply via email to