Search code examples
c#.netjsonjettison

Parse/Encode JSON without Deserializing/Serializing classes


I'm looking for a JSON parser and encoder for .NET that can parse JSON into its own data structure which I can then navigate, as opposed to directly deserializing it into a class. In Java, I use Jettison's JSONObject and JSONArray which is dead easy to use.

There are a number of reasons why I don't want to (de)serialize:

  1. Serializers tend to add metadata to the JSON and require that metadata for deserialization (e.g. fastJSON and JSON.NET add type info).
  2. I don't want the hassle of having to create a bunch of classes to handle all the different types of data. Also, I want to be able to ignore fields I'm not interested in rather than have to add properties to them.

Is there anything available or do I have to port a subset of Jettison?


Solution

  • The disadvantages of serialization that you point out aren't really there, at least in the case of JSON.NET:

    1. JSON.NET doesn't add any metadata by default. You can tell it to add the metadata if you need it (for example, when one property can hold values of different types), but it's optional.
    2. You replace the hassle of creating classes with the hassle of working with strings and casts and I think that's much worse. Also, you can ignore fields you're not interested in, just don't add them to your types.

    But, if you really want to do that, you can. The equivalent types are JObject and JArray, so, if you want to deserialize some object, use:

    JObject obj = JsonConvert.DeserializeObject<JObject>(json);
    

    As another option, you don't have to specify the type you want at all, ant it will return either JObject or JArray:

    object objectOrArray = JsonConvert.DeserializeObject(json);