Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I deserialize json to anonymous type in c#?

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

like image 973
Elad Benda Avatar asked Sep 20 '11 13:09

Elad Benda


People also ask

What is an anonymous type in C?

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.

How do I deserialize a JSON file?

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.

What is the difference between serialize and deserialize JSON?

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.

Is polymorphic deserialization possible in System text JSON?

There is no polymorphic deserialization (equivalent to Newtonsoft. Json's TypeNameHandling ) support built-in to System.


1 Answers

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.)

like image 67
Jon Skeet Avatar answered Oct 17 '22 14:10

Jon Skeet