Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 396
Connor Clark Avatar asked Oct 30 '14 19:10

Connor Clark


1 Answers

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.

like image 106
Andrew Whitaker Avatar answered Oct 18 '22 15:10

Andrew Whitaker