Use protobuf-net to convert json into object - c#

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.

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.

Related

What base serializer does protobuf-net use to output byte array?

Does protobuf-net use BinaryFormatter or other formatter as an base serializer to serialize an object as byte[], and then write to stream?
add:
I use protobuf-net serialize data and want to deserialize in golang, is there any serializer can do the work in go?
Protobuf-net is a ground-up implementation of the "Protocol Buffers" serialization format, with an idiomatic .NET API. It has nothing to do with BinaryFormatter (although it can be used to create custom ISerializable implementations for use with BinaryFormatter, if you still play in that world).
If you want to use Protocol Buffers (protobuf) with Go, just pick one of the Go implementations from this list.
Most protobuf libraries are "contract first", meaning: you need a .proto schema; to get that from protobuf-net, use Serializer.GetProto<T>() for the T that you are using as a root type.
Note: if you are serializing DateTime or TimeSpan, it would be a good idea to make sure that you are using DataFormat.WellKnown on those members - it'll make it much easier to work in a cross-platform way with other libraries; but note that this is not a data-compatible change: it fundamentally changes how those values are stored, so : if you have existing data you'll need to think of a migration strategy.

Loose typing option for Json.NET similar to GSON

In GSON, you can deserialize into a JsonObject, which in turns allows you to access JsonElements and call methods such as getAsString(), getAsInt(), etc...
This is incredibly useful for my use case: I am serializing data with JSON and sending it over a network. Data is sent along with protocol identifiers which tells the client how to process the data. I do not want to create a class for every different sort of protocol, so deserializing as a JsonObject allows me a lot of flexibility.
I can't find an analogous way to do this in C#. I figure I need to roll my own JsonElement/Object/Array/Primitive hierarchy, but I don't really know where to begin. Is that even the best way to do it?
I want to:
Deserialize json in C# into a structure which lets me access data as specific types, without using a class "skeleton" for the data.
EDIT:
I am restricted to .NET 3.5
JSON.NET can do this--you don't need to deserialize into a class:
int value = JObject.Parse(myJsonString)["property"]["subProperty"].Value<int>();
See the documentation for LINQ to JSON for more information.

JSON Serialization Output Contains Count Property

I'm trying to serialize an array of objects into JSON in C#. By array I mean something like Object[] (not Array<Object>), I'm using a JsonMediaTypeFormatter as part of MVC (the serialization is happening automatically as part of the framework but I can override it). The output contains {"count":2,"value":[{...},{...},...]}" where the ... is the json representation of the object. I've looked around and haven't found much information about suppressing this behavior. I want the output to just be the [{...},{...},...] rather than the object with count and values properties. Does anyone know how to achieve this without manually writing the code to do the serialization?
You could consider an alternative framework like the JSON.NET framework. I don't know how much you can customize if you are using an in-built .NET object since there are public properties that are not being ignored. Not using the JSONMediaTypeFormatter much, if it allows you to ignore properties, consider overriding List or ArrayList to hide certain attributes.
I would recommend not returning an array directly as there is a security flaw that could be compromised in a client browser (if that is the consumer). See this reference to find out more.

What's the difference between DataContractJsonSerializer and JavaScriptSerializer?

The .NET Framework ships with System.Runtime.Serialization.Json.DataContractJsonSerializer and System.Web.Script.Serialization.JavaScriptSerializer, both of which de/serialize JSON. How do I know when to choose one of these types over the other? MSDN doesn't make it clear what their relative advantages are.
We have several projects that consume or emit JSON, and the class selected for each thus far has depended on the opinion of the primary dev on each project. Some are simple, two have complex logic regarding producing managed types from JSON (the types do not map closely to the streams) but don't have any emphasis on speed, one requires speed. None interact with WCF, at least as of now.
While I'm interested in alternative libraries, I am hoping that somebody might have an answer to my question too.
The DataContractJsonSerializer is intended for use with WCF client applications where the serialized types are typically POCO classes with the DataContract attribute applied to them. No DataContract, no serialization. The mapping mechanism of WCF makes the sending and receiving very simple, but only if your platform is homogeneous. If you start mixing in different toolsets, your program might go sideways.
The JavaScriptSerializer can serialize any type, including anonymous types (one way), and does so in a more conformant way. You lose the "automagic" of WCF, but you gain more integration options.
As you can see by the comments, there are a lot of options out there for AJAX serialization, and to address your speed vs. maintainability questions, it might be worth investigating them to find a solution that meets the needs of all the teams, to reduce maintainability issues in the long term as everybody does things their own way.
2014-04-07 UPDATE:
I suggest using JSON.NET if you can. See http://james.newtonking.com/json Feature Comparison for a review of the 3 libraries considered in this question.
2015-05-26 UPDATE:
If your company requires the use of commercially licensable products, or you need every last bit of performance, you may also want to check out https://servicestack.net/.
Both do approximately the same but using very different infrastructure thus applying different restrictions on the classes you want to serialize/deserialize and providing different degree of flexibility in tuning the serialization/deserialization process.
For DataContractJsonSerializer you must mark all classes you want to serialize using DataContract atrtibute and all members using DataMember attribute. As well as if some of you classes have enum members, then the enums also must be marked as DataContract and each enum member - with EnumMember attribute.
Also DataContractJsonSerializer allows you fine control over the whole process of serialization/deserialization by altering types resolution logic and replacing the types you serialize with surrogates.
For JavaScriptSerializer you must provide parameterless constructor if you plan on deserializing objects from json string.
For me, I usually use JavaScriptSerializer in presentation logic, where there's a simple model I want to render in Json together with page, without additional ajax requests. And I even usually don't have to deserialize them back to c# - so there's no overhead at all. But if it's persistence logic, where I want to save objects into a data store (usually no-sql storage), to load them later, I prefer using DataContractJsonSerializer because the overhead of putting attributes is worth of flexibility in the serialization/deserialization process tuning, especially when it comes to loading of serialized data into the objects of the newer version, with updated definitions
Personally, I think that DataContractJsonSerializer reeks of over-engineering. I'd skip it and go with JavaScriptSerializer. In the event where JavaScriptSerializer isn't available, you can use FridayThe13th (a library I wrote ;p).

a question about serialization

What is a better approach to serialize custom class: using XMLSerializer or BinarryFormatter and [Serializable] attribute on class?
It's not possible to answer this, without knowing how you will use the resulting file, and the lifetime of it.
The decision is based on the fact that it is harder to "upgrade" the binary format. If your object model changes, it won't deserialise correctly. But if you've implemented a custom XML serialisation/deserialisation, then you can handle the "new" cases appropriately, and life will be good.
So decide more about how you will use it, who you are sharing information with, and what the possible changes to the model are.
FWIW, I sometimes use both types of serialisation in a given project.
That really depends on how you use the serialized class. If you want to pass it to other programs or want to easily debug it, use XML (but mind that XMLSerializer might produce non-compliant XML output, like multiple root elements).
In all other cases, you can use the binary formatter. But note that XML is more suitable if you change the class later - you can use XMLIgnore and the like to keep the XML format intact.
The decision will sometimes also be made for you based on what the serialized output will be used for - while you could expose a WebService to take a binary array that is a binary serialized item, you couldn't utilize the web service easily from anything but .Net (and the end client would probably need a reference to the type).
Using XML means that the service could be exposed to any end client regardless of the platform/environment on the end client

Categories