I read from the DB a long json. I want just one attribute of that json.
I have got two options: a. Create an interface for that json and deserialize to that interface. (Is it an overkill as I need just one attribute ?) b. Find the substring I need (regex? )
which one is preferred ?
update: I'm using .net 3.5
What Are Anonymous Types in C#? Anonymous types are class-level reference types that don't have a name. They allow us to instantiate an object without explicitly defining a type. They contain one or more read-only properties. The compiler determines the type of the properties based on the assigned values.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.
There is no polymorphic deserialization (equivalent to Newtonsoft. Json's TypeNameHandling ) support built-in to System.
Why don't you deserialize using JSON.NET's "LINQ to JSON" approach (JObject
etc) and just ask for the value you need by name?
That's sufficiently dynamic so you don't need to create an interface for everything, but it's a lot less brittle than using a regex.
JObject json = JObject.Parse(text);
JToken value = json["foo"]["bar"];
(I believe JSON.NET also support's dynamic
in .NET 4, but there's no particular need to use it here.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With