Deserialize JSON to anonymous object
JSON.Net is a powerful library to work with JSON in .Net
There's a method DeserializeAnonymousType you can tap in to.
Update: Json.Net is now included with ASP.Net, however my latest favorite that I use is JsonFX. It's got great linq support as well, check it out.
Update 2: I've moved on from JsonFX, and currently use ServiceStack.Text, it's fast!
Deserialize anonymous type with System.Text.Json
As of .Net 5.0, deserialization of immutable types -- and thus anonymous types -- is supported by System.Text.Json
. From How to use immutable types and non-public accessors with System.Text.Json:
System.Text.Json
can use a parameterized constructor, which makes it possible to deserialize an immutable class or struct. For a class, if the only constructor is a parameterized one, that constructor will be used.
As anonymous types have exactly one constructor, they can now be deserialized successfully. To do so, define a helper method like so:
public static partial class JsonSerializerExtensions
{
public static T? DeserializeAnonymousType<T>(string json, T anonymousTypeObject, JsonSerializerOptions? options = default)
=> JsonSerializer.Deserialize<T>(json, options);
public static ValueTask<TValue?> DeserializeAnonymousTypeAsync<TValue>(Stream stream, TValue anonymousTypeObject, JsonSerializerOptions? options = default, CancellationToken cancellationToken = default)
=> JsonSerializer.DeserializeAsync<TValue>(stream, options, cancellationToken); // Method to deserialize from a stream added for completeness
}
And now you can do:
var token = JsonSerializerExtensions.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
Demo fiddle here.
Deserializing json to anonymous object in c#
C# 4.0 adds dynamic objects that can be used. Have a look at this.
How do I deserialize an array of JSON objects to a C# anonymous type?
The solution is:
string json = @"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
var definition = new[] { new { Name = "" } };
var result = JsonConvert.DeserializeAnonymousType(json, definition);
Of course, since result
is an array, you'll access individual records like so:
string firstResult = result[0].Name;
You can also call .ToList()
and similar methods on it.
Deserialize JSON to anonymous object in asp.net core
Based on your input xml and output json, you cannot directly convert to JSON. Here is one approach using LINQ
to get desired object and Serialize using JsonConvert
var strFile = File.ReadAllText("XMLFile1.xml");
var grades = xdoc.Descendants("KEY")
.Where(x => x.Attribute("name").Value == "grades")
.Descendants("SINGLE")
.Select(y => new Grades
{
Courseid = y.Descendants("KEY").Where(z => z.Attribute("name").Value == "courseid").Select(a => a.Element("VALUE").Value).FirstOrDefault(),
Grade = y.Descendants("KEY").Where(z => z.Attribute("name").Value == "grade").Select(a => a.Element("VALUE").Value).FirstOrDefault(),
Rawgrade = y.Descendants("KEY").Where(z => z.Attribute("name").Value == "rawgrade").Select(a => a.Element("VALUE").Value).FirstOrDefault(),
Rank = y.Descendants("KEY").Where(z => z.Attribute("name").Value == "rank").Select(a => a.Element("VALUE").Value).FirstOrDefault(),
});
Console.WriteLine(JsonConvert.SerializeObject(grades));
Deserialize JSON object into dynamic object using Json.net
Json.NET allows us to do this:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);
Output:
1000
string
6
Documentation here: LINQ to JSON with Json.NET
See also JObject.Parse and JArray.Parse
Parse JSON into anonymous object[] using JSON.net
you can deserialize by example, using an anonymous type like this:
string jsonString = "{name:\"me\",lastname:\"mylastname\"}";
var typeExample = new { name = "", lastname = "",data=new int[]{1,2,3} };
var result=JsonConvert.DeserializeAnonymousType(jsonString,typeExample);
int data1=result.data.Where(x => 1);
Other way in Json.Net it's using a dynamic object like this:
dynamic result2=JObject.Parse(jsonString);
Related Topics
C# Null Coalescing Operator Equivalent for C++
How to Access Resourcedictionary in Wpf from C# Code
How to Dllexport a C++ Class for Use in a C# Application
How to Get the Value of a Session Variable Inside a Static Method
How to Pass Variable into SQLcommand Statement and Insert into Database Table
Capturing Count from an SQL Query
Linq: How to Exclude Condition If Parameter Is Null
Why Does a Float Variable Stop Incrementing at 16777216 in C#
Xamarin Android Alarm Manager Issue
What Is the Equivalent of "Case When Then" (T-Sql) with Entity Framework
In C# Wpf, Why Is My Tabcontrol's Selectionchanged Event Firing Too Often
Error While Using Executenonquery C#
How to Compare Two Objects in Unit Test
Dotnet.Highcharts: Cost Not Plotted Against the Correct Date
When Should I Use Out Parameters
Escaping the Escape Character Does Not Work - SQL Like Operator
ASP.NET Core Disable Authentication in Development Environment