1

I have been provided a c# class generated through protogen.

I have a json response which I want to convert into object(map to the class generated from protogen).

How can I achieve this ? The Json that I have is like:

    Test {Id:"0000001" InsertDateTime:"4/12/2018 01:01:01" ModifyDateTime:"4/12/2018 01:05:10" ParentId:"0000001"
Sample{Id:"0000002" InsertDateTime:"4/12/2018 01:01:01" ModifyDateTime:"4/12/2018 01:05:10"}
}

The main class name is 'Test' and it has int, string properties as well as properties of type 'class' as well.

I want to convert this Json to 'protogen' generated class object.

Nilesh Sarvaiya
  • 49
  • 3
  • 11
  • if you have a concrete example of the JSON and the object model (`class` etc) that you're struggling with, it would make it *much* easier to give a specific example as an answer – Marc Gravell Apr 12 '18 at 10:02
  • re the edit: that isn't valid JSON; and it would be really useful to see the object model that this is meant to map to – Marc Gravell Apr 12 '18 at 14:23

1 Answers1

1

protobuf-net only implements the binary Protocol Buffers (ProtoBuf) specification.

It is unclear whether by "json" you mean "general purpose JSON, nothing to do with ProtoBuf", or whether you mean "the Protocol Buffers JSON format added around 3.0".

If you mean general purpose JSON: then usually just about any JSON serializer will work fine - Json.NET is a good default, but other JSON serializers exist. This is because protobuf-net tries to work with idiomatic .NET objects, which means that it tends to play very nicely with other tools that work with idiomatic .NET objects.

If you mean the ProtoBuf-specific JSON, then I would suggest using Google's official C# ProtoBuf library, which implements this. I simply haven't had need or time to add support for this into protobuf-net, and to date adding it has been a very low priority for me - I simply haven't seen anyone asking for it from me.


If you have generic JSON, but the JSON layout is different to your protobuf model, then frankly I would recommend having two DTO models:

  • one that is designed to work with your JSON data and your chosen JSON serializer (such as Json.NET)
  • one that is designed to work with your ProtoBuf data and your chosen ProtoBuf serializer (such as protobuf-net)

and simply map between the two representations with regular C# code (or any auto-mapper tool of your choosing).

You can sometimes fight a serializer library to get it work with an object model that doesn't match the shape of the data, but in my experience this is a bad use of time and leads to brittle, buggy code.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900