Reputation: 19
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!");
}
}
}
Upvotes: 1
Views: 141
Reputation: 3873
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"]);
Upvotes: 1
Reputation: 116168
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; }
}
Upvotes: 1