Proto3 JSON is there a MessageToJsonString method

2,647 views
Skip to first unread message

Chad Beaulac

unread,
Jun 15, 2016, 11:17:56 AM6/15/16
to Protocol Buffers
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






Feng Xiao

unread,
Jun 15, 2016, 3:57:12 PM6/15/16
to Chad Beaulac, Protocol Buffers
Sorry, we definitely should add these methods for convenience but just don't get time for it yet. Could you help file a github issue? Or better help us add these two methods?
 

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+u...@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Chad Beaulac

unread,
Jun 15, 2016, 4:19:28 PM6/15/16
to Protocol Buffers, cabe...@gmail.com
Hi Feng,
I just wrote this Github issue: https://github.com/google/protobuf/issues/1690
I'll look into doing it too.

-Chad
Reply all
Reply to author
Forward
0 new messages