package com.tzld.piaoquan.recommend.model.grpc.client;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dyp
 */
@Slf4j
public class ProtobufUtils {
    public static String toJson(MessageOrBuilder message) {
        if (message == null) {
            return "";
        }
        try {
            return JsonFormat.printer().includingDefaultValueFields().print(message);
        } catch (InvalidProtocolBufferException e) {
            log.error("ProtobufUtils toJson error", e);
        }
        return "";
    }

    public static void fromJson(String json, Message.Builder builder) throws InvalidProtocolBufferException {
        JsonFormat.parser().merge(json, builder);
    }

}
