Can I deserialize json to anonymous type in c#?
Asked Answered
O

7

15

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

Outstare answered 20/9, 2011 at 13:28 Comment(0)
M
27

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

Missioner answered 20/9, 2011 at 13:31 Comment(0)
L
18

Regex must be absolutely out of any discussion. Just forget about it, it's as if it never existed.

Creating and working with strong types is a good thing and probably the way I would go.

But if you want, you could also use dynamic:

class Program
{
    static void Main()
    {
        var json = "{ 'foo': { 'bar': 'bar value', 'baz': [ 1, 2, 3 ] } }";
        var serializer = new JavaScriptSerializer();
        dynamic value = serializer.DeserializeObject(json);
        Console.WriteLine(value["foo"]["baz"][1]);
    }
}

prints 2 on the console.

Lingerfelt answered 20/9, 2011 at 13:32 Comment(2)
I'm using c# 3.5 I don't think there is dynamic type. right ?Outstare
@Elad Benda, no there isn't. Well then you could use Json.NET which offers a similar syntax.Lingerfelt
S
2

On .NET 4:

You can do something kind of like what you want minus the need for regex (and you shouldn't use regex for something like this!) by using the dynamic feature of C# 4.0 described here: http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx

The only downside is that you can't guarantee what the exact structure of the object is.

The upswing is that instead of accessing members via yourDynamicObject['blah'], it's the more duck-type-ish yourDynamicObject.blah

On .NET 3.5:

You can use Json.NET: http://json.codeplex.com/

Sokol answered 20/9, 2011 at 13:31 Comment(0)
E
1

Finding the substring is a dangerous optimisation.

Is it worth optimising the process (compared to a JSON deserialization) and safe to do such a lookup ? We can't answer yes because it's mostly dependent on the context. But I feel like saying NO because it's obviously looking for trouble: Even if it works now, it may get broken in the future when the structure or contents of you object changes.

Em answered 20/9, 2011 at 13:36 Comment(0)
F
1

Old thread, but here goes another method on .NET 3.5: you can cast the object returned by DeserializeObject to a Dictionary<String, Object>. It's kind of the same solution as using the .NET 4.0 dynamic keyword:

JavaScriptSerializer serializer = new JavaScriptSerializer();
Object obj = serializer.DeserializeObject("{ 'name': 'vinicius fonseca', 'age': 31 }");
Dictionary<String, Object> ret = (Dictionary<String, Object>)obj;
Console.WriteLine(ret["name"].GetType().Name); // Output: String
Console.WriteLine(ret["name"].ToString()); // Output: vinicius fonseca
Console.WriteLine(ret["age"].GetType().Name); // Output: Int32
Console.WriteLine(ret["age"].ToString()); // Output: 31

Hope it helps someone.

Regards

Felonry answered 6/3, 2013 at 15:27 Comment(0)
B
1

You can do:

var result = JsonConvert.DeserializeAnonymousType(json, new { Foo="", Bar=""});

This will return a dynamic object with the fields you defined.

Baggage answered 25/5, 2015 at 13:39 Comment(1)
Could you please elaborate more your answer adding a little more description about the solution you provide?Thais
T
0

It depends.

Option A is the more strict, disciplined, and formal way. Yet, again like you said it may be overkill. How fat is that json? Long term, Option A leaves the future potential possibility that you may need to use more than one property.

Option B is definitely more informal and straight forward. It will definitely work today, but may require a different solution in the future.

Thus, maybe you would want to wrap the entire process in a method to hide the implementation from the calling client. Return your custom object with only the lone property populated. Then, if the need arises in the future you can change the method to utilize full tilt deserialization.

Note: I do not think deserialization to an anonymous type in C# 3.5 is possible.

Trevor answered 20/9, 2011 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.