How to get JavaScriptSerializer to treat a sub-object like a regular old string?

My JSON goes into my program as follows:

{
    "Foo": "some string",
    "Bar": { "Quux" : 23 }
}

How can I use JavaScriptSerializerfor parsing , but treat the value of Bar as a string instead of a sub-object? The code below throws an exception, as expected.

After deserializing, I want to thing.Barcontain a string { "Quux" : 23 }. Is there an easy way to do this?

class Thing
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        string json = "{ \"Foo\": \"some string\", \"Bar\": { \"Quux\": 23 }}";
        var serializer = new JavaScriptSerializer();
        var thing = serializer.Deserialize<Thing>(json);
    }
}
+3
source share
2 answers

You want to implement your own JavaScriptConverter to do this ... here is an example ...

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

namespace ConsoleApplication1
{
    [Serializable]
    public class Thing
    {
        public string Foo { get; set; }
        public string Bar { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"Foo\":\"some string\",\"Bar\":{\"Quux\":23}}";
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new JavaScriptConverter[] {
                new StringConverter()           
            });
            var thing = serializer.Deserialize<Thing>(json);

            Console.WriteLine(thing.Bar);
        }
    }

    public class StringConverter : JavaScriptConverter
    {
        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(string) })); }
        }

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

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            var i = dictionary.First();
            return "{ \"" + i.Key + "\" : " + i.Value + " }";
        }
    }
}
+1
source

Have you tried the contents of Bar in quotation marks?

{
    "Foo": "some string",
    "Bar": "{ 'Quux' : 23 }"
}
0
source

Source: https://habr.com/ru/post/1792837/


All Articles