【问题标题】:Serialise IMessage Protobuf to json C#将 IMessage Protobuf 序列化为 json C#
【发布时间】:2020-10-23 08:58:58
【问题描述】:

我有一个如下的原型文件:

syntax = "proto3";

package _abbbd3832ad747a0a1b0cd1b3c6d6579;

enum Allocator {
  // This needs to be here as a zero value.
  DO_NOT_REMOVE = 0;
  VALUE = 1;
};

enum StandardEventCodes {
  // Signal: N/A
  POWER_UP = 0;

  // Signal: N/A
  WAKE_UP = 1;

  // Signal: N/A
  POWER_OR_WAKE_UP = 2;
};

enum StandardFilterCodes {
  // Signal: The current profile.
  IS_CURRENT_PROFILE = 0;

  // Signal: The restricted mode
  // 0 - unrestricted
  // 1 - restricted
  // 2 - transport
  // 3 - invalid
  IS_RESTRICTED_MODE = 1;
};

enum StandardActionCodes {
  // Signal: The profile to apply.
  APPLY_PROFILE = 0;
};

message Config {
  message Profile {
    enum State {
      ACTIVE = 0;
      SLEEP = 1;
      HIBERNATE = 2;
    };

    // The profile's state.
    State state = 1;

    // What will wake the device up (input, adc_threshold, cell, etc).
    uint32 wakeup_mask = 2;

    // How long to wait before applying this profile in seconds.
    uint32 delay_s = 3;
  };

  repeated Profile profiles = 1;
};

我已经设法从 protoc 编译器生成了一个 cs。但是,是否可以通用生成一个json文件。

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                            where t.GetInterfaces().Contains(typeof(IMessage))
                                     && t.GetConstructor(Type.EmptyTypes) != null
                            select Activator.CreateInstance(t) as IMessage;

foreach (var instance in instances)
{
    string json = instance.ToString();  // doesnot work
    Console.WriteLine(instance.GetType().GetNestedTypes().ToString()); // doesnot work
}

请提出建议。

【问题讨论】:

    标签: c# json protocol-buffers proto


    【解决方案1】:

    看看Json.Net

    string output = JsonConvert.SerializeObject(instances)
    

    Json 通常在没有注释类的情况下工作。但是一些特性,比如序列化派生对象可能需要用属性注释类。这种带有注释类的模型在 .net 中很常见。我会考虑使用Protobuf.Net,因为它遵循相同的模型,并且可以很容易地为 protobuf 和 json 序列化使用相同的类。

    【讨论】:

      【解决方案2】:

      我编写了一个小型库,可以帮助您解决问题。它将对 Google.Protobuf 类型的支持添加到 System.Text.Json。

      您可以从 nuget 获取它 --> https://www.nuget.org/packages/Protobuf.System.Text.Json/

      它非常易于使用。您需要做的就是在 JsonSerializerOptions 上启用 protobuf 支持。

      var msg = new SimpleMessage
      {
          DoubleProperty = 2.5d
      };
      
      var jsonSerializerOptions = new JsonSerializerOptions();
      jsonSerializerOptions.AddProtobufSupport();
      var serialized = JsonSerializer.Serialize(msg, jsonSerializerOptions);
      

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-30
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多