Skip to content
Fix Code Error

Deserialize JSON into C# dynamic object?

March 13, 2021 by Code Error
Posted By: Anonymous

Is there a way to deserialize JSON content into a C# 4 dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.

Solution

If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class:

dynamic data = Json.Decode(json);

It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that’s helpful! However if you cannot assume the client environment includes this DLL, then read on.


An alternative deserialisation approach is suggested here. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to System.Web.Extensions from your project:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}

#region Nested type: DynamicJsonObject

private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;

public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}

public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}

private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:"{1}""""

Answered By: name

Related Articles

  • error LNK2005: ✘✘✘ already defined in…
  • npm install error in vue
  • Is CSS Turing complete?
  • Could not load file or assembly 'Newtonsoft.Json' or…
  • How to avoid a System.Runtime.InteropServices.COMException?
  • Detect if Visual C++ Redistributable for Visual…
  • Could not load file or assembly…
  • Maven2: Missing artifact but jars are in place
  • Error Message : Cannot find or open the PDB file
  • How do I install soap extension?
  • Error 'Map', but got one of type 'Null' flutter web…
  • How to solve Internal Server Error in Next.Js?
  • useEffect Error: Minified React error #321 (GTM…
  • Replace every other instance of a string
  • UnsatisfiedDependencyException: Error creating bean…
  • Spring data jpa- No bean named…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • Error: container has not been made global - how to solve?
  • MSBuild doesn't copy references (DLL files) if using…
  • Parse JSON in C#
  • Error creating bean with name
  • Could not load file or assembly 'System.Data.SQLite'
  • Sorting A Table With Tabs & Javascript
  • How can I specify a [DllImport] path at runtime?
  • GLYPHICONS - bootstrap icon font hex value
  • Which maven dependencies to include for spring 3.0?
  • .Net picking wrong referenced assembly version
  • How can I use a reportviewer control in an asp.net…
  • Compile a DLL in C/C++, then call it from another program
  • Visual Studio debugging/loading very slow
  • How to download Xcode DMG or XIP file?
  • System.IO.FileNotFoundException: Could not load file…
  • Spring Boot - Cannot determine embedded database…
  • System.Data.SqlClient.SqlException: Login failed for user
  • An item with the same key has already been added
  • The type or namespace name 'System' could not be found
  • How to add Typescript to a Nativescript-Vue project?
  • The type or namespace name does not exist in the…
  • "An exception occurred while processing your…
  • Why does C++ code for testing the Collatz conjecture…
  • How do I initialize a TypeScript Object with a JSON-Object?
  • How to fix "Referenced assembly does not have a…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • How to extract an assembly from the GAC?
  • Could not load file or assembly 'System.Web.Mvc'
  • Building executable jar with maven?
  • Is it possible to apply CSS to half of a character?
  • How to Load an Assembly to AppDomain with all…
  • Could not load type…
  • Apache server keeps crashing, "caught SIGTERM,…
  • Maven Could not resolve dependencies, artifacts…
  • Configuration Error: ASP.NET MVC3
  • How do I control c++ DLL debug symbols loading?
  • Loading DLLs at runtime in C#
  • After a little scroll, the sticky navbar just is not…
  • Eclipse Spring Boot need declare Maven dependency explicitly
  • Testing aurelia customElement with bindable and dependencies
  • Launching Spring application Address already in use
  • Could not load file or assembly System.Net.Http,…
  • The 'packages' element is not declared
  • Avoid creating new session on each axios request laravel
  • Disable Logback in SpringBoot
  • What are the currently supported CSS selectors…
  • Crystal Reports 13 And Asp.Net 3.5
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Aurelia bundling issue with virtual directory
  • The located assembly's manifest definition does not…
  • How can I mock an ES6 module import using Jest?
  • How to observe embedded arrays in Ember objects?
  • Exception in thread "main"…
  • Multipart File Upload Using Spring Rest Template +…
  • Exception in thread "JobGenerator"…
  • Web Application Problems (web.config errors) HTTP…
  • How should a model be structured in MVC?
  • The superclass "javax.servlet.http.HttpServlet" was…
  • Error: the entity type requires a primary key
  • JQuery, Spring MVC @RequestBody and JSON - making it…
  • Can Json.NET serialize / deserialize to / from a stream?
  • How to download and save an image in Android
  • Correct Way to Load Assembly, Find Class and Call…
  • Error creating bean with name 'entityManagerFactory'…
  • ember.js, ember-cli: Outlets not nesting properly
  • Download Excel file via AJAX MVC
  • java.lang.ClassNotFoundException:…
  • Upvote and Downvote with Backbone, Express and Mongoose
  • MVC 4 @Scripts "does not exist"
  • How can I send emails through SSL SMTP with the .NET…
  • grid controls for ASP.NET MVC?
  • How to handle static content in Spring MVC?
  • TypeScript metadata reflection references other…
  • Download & Install Xcode version without Premium…
  • "The system cannot find the file specified"
  • Logging best practices
  • How to change Windows 10 interface language on…
  • Could not load file or assembly or one of its…
  • How to get active user's UserDetails
  • Error Stack Overflow when trying to hide buttons in…
  • What exactly are DLL files, and how do they work?
  • Download a file with Android, and showing the…
  • org.springframework.beans.factory.NoSuchBeanDefiniti…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to get the selected radio button’s value?

Next Post:

Combining “LIKE” and “IN” for SQL Server

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error