6

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

Connor Clark
  • 671
  • 7
  • 15
  • 1
    possible duplicate of [Deserialize JSON into C# dynamic object?](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Edin Oct 30 '14 at 19:13
  • 1
    Those solutions would work great, but I am restricted to .NET 3.5. So, no dynamics. – Connor Clark Oct 30 '14 at 19:54

1 Answers1

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307