package com.tzld.piaoquan.recommend.server.client;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;

/**
 * @author dyp
 */
public class ProtobufUtils {
    public static String toJson(MessageOrBuilder message) throws InvalidProtocolBufferException {
        if (message == null) {
            return "";
        }
        return JsonFormat.printer().includingDefaultValueFields().print(message);
    }

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

//
//    public static void main(String[] args) throws InvalidProtocolBufferException {
//        RecommendResponse.Builder builder = RecommendResponse.newBuilder();
//        builder.setResult(Result.newBuilder().setCode(6).setMessage("success"));
//        String json = JsonFormat.printer().includingDefaultValueFields().print(builder);
//        System.out.println(json);
//
//        RecommendResponse.Builder builder2 = RecommendResponse.newBuilder();
//        JsonFormat.parser().merge(json, builder2);
//        System.out.println(JsonFormat.printer().print(builder2));
//    }
}
