cosmin.danisor
cosmin.danisor

Reputation: 963

C# protobuf-net serialized object to java

So I have a small problem:

A message is sent using MQTT, it consists of a series of serialized objects using protobuf-net in C# (I can't modify this code, but I have access to the source). At the other end i receive the serialized objects in Java, the problem is I can't seem to be able to deserialize the objects using protobuf, if anyone ever had this problem and solved it, please help :)

Example of object from C#:

using ProtoBuf;

namespace Concentrator.Services
{
[ProtoContract]
public class MeterID
{
    private byte[] _id;

    [ProtoMember(1)]
    public byte[] ID
    {
        get { return _id; }
        set { _id = value.Length == 16 ? value : null; }
    }

    [ProtoMember(2)] public string MeterType;
}
}

My attempt at recreating the same object in Java (the .proto file):

syntax = "proto2";

 package mqtt.entity;

 option java_package = "mqtt.entity";
 option java_outer_classname = "ProtoMeter";
 message Meter {
    optional bytes ID = 1;
     optional string MeterType = 2;
  }

  message MeterID {
     repeated Meter mid = 1;
 }

A solution to this example would be a huge help, Thanks a lot.

The code where the object is deserialized in C#:

var ms = new MemoryStream(data, 7, data.Length - 9)
var res = Serializer.Deserialize<List<MeterID>>(ms);

this works in C#, I'm trying to achieve the same thing in java

Upvotes: 1

Views: 2650

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064044

The message in your C# code matches just:

message MeterID {
    optional bytes ID = 1;
    optional string MeterType = 2;
}

There is no need for a 2-level model (unless you're using *WithLengthPrefix in the C# code). You can also get that output by using:

var proto = Serializer.GetProto<MeterID>();

With your edit, a List<MeterID> could be mapped as

message List_MeterID {
    repeated MeterID items = 1;
}

to be used in combination with the previous MeterID fragment. Which is what you have in the question. So it comes down to "what currently happens?".

Upvotes: 3

burning_LEGION
burning_LEGION

Reputation: 13460

try regenerate proto-file by GetProto<T>

Upvotes: 1

Related Questions