How Do I Let the C# Compiler Ignore Primitive Types and Numeric String Values for JSON String in Dynamic Data?

150 Views Asked by At

I am getting compiler errors when I am parsing a JSON String when the primitive type "string" and numeric string values of "01", "02" are used for dynamic data. I am using the JavaScriptSerializer with .Net 4.0 installed. See the listing of the C# Code Snippet below:

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

namespace DynamicJsonParser
{
    class Program
    {
       static void Main(string[] args)
       {
           const string json = "{\"options\":{\"01\":{\"enabled\":01,\"string\":\"Battery\"},\"02\":{\"enabled\":00,\"string\":\"Steering Sensor\"}}}";
           var serializer = new JavaScriptSerializer();
           serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
           dynamic data = serializer.Deserialize<object>(json);

           // Compiling error when I use the primitive types
           // and string numerical values for dynamic data:
           // "01,02,string" for the JSON String.
           // How do I let the compiler know that I am using the 
           // above primitive types and string numerical values
           // for dynamic data instead in the JSON String?
           Console.WriteLine(data.options.01.enabled); // Compiler Error.
           Console.WriteLine(data.options.01.string);  // Compiler Error.
           Console.WriteLine(data.options.02.enabled); // Compiler Error.
           Console.WriteLine(data.options.02.string);  // Compiler Error.
           Console.WriteLine("Done!");
       }
    }
}
2

There are 2 best solutions below

2
On

That's not really the correct way to reference the deserialized data. Instead, you can do the following:

const string json = "{\"options\":{\"01\":{\"enabled\":01,\"string\":\"Battery\"},\"02\":{\"enabled\":00,\"string\":\"Steering Sensor\"}}}";
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<dynamic>(json);

Console.WriteLine(data["options"]["01"]["enabled"]);
Console.WriteLine(data["options"]["01"]["string"]);
Console.WriteLine(data["options"]["02"]["enabled"]);
Console.WriteLine(data["options"]["02"]["string"]);
6
On

You don't need dynamic. You can deserialize to Dictionary.

string json = "{\"options\":{\"01\":{\"enabled\":01,\"string\":\"Battery\"},\"02\":{\"enabled\":00,\"string\":\"Steering Sensor\"}}}";

var serializer = new JavaScriptSerializer();
var root = serializer.Deserialize<Root>(json);

foreach (var item in root.options)
{
    Console.WriteLine(item.Key + ": " + item.Value.enabled + "," + item.Value.@string);
}

public class Item
{
    public int enabled { get; set; }
    public string @string { get; set; }
}

public class Root
{
    public Dictionary<string, Item> options { get; set; }
}