Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize json to an object with catch all dictionary property

Tags:

json

c#

json.net

I would like to use JSON.net to deserialize to an object but put unmapped properties in a dictionary property. Is it possible?

For example given the json,

 {one:1,two:2,three:3}

and the c# class:

public class Mapped {
   public int One {get; set;}
   public int Two {get; set;}
   public Dictionary<string,object> TheRest {get; set;}
}

Can JSON.NET deserialize to an instance with values one=1, two=1, TheRest= Dictionary{{"three,3}}

like image 514
PhilHoy Avatar asked Jul 26 '11 12:07

PhilHoy


People also ask

Can JSON serialize dictionary?

Json can't serialize Dictionary unless it has a string key. The built-in JSON serializer in . NET Core can't handle serializing a dictionary unless it has a string key.

How do you serialize a dictionary to a JSON string?

Simple One-Line Answer. This code will convert any Dictionary<Key,Value> to Dictionary<string,string> and then serialize it as a JSON string: var json = new JavaScriptSerializer(). Serialize(yourDictionary.

What is Serialised JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Can JSON serialize a list?

Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.


2 Answers

The easiest way to do this is to use the JsonExtensionData attribute to define a catch all dictionary.

Example from the Json.Net documentation:

public class DirectoryAccount
{
    // normal deserialization
    public string DisplayName { get; set; }

    // these properties are set in OnDeserialized
    public string UserName { get; set; }
    public string Domain { get; set; }

    [JsonExtensionData]
    private IDictionary<string, JToken> _additionalData;

    [OnDeserialized]
    private void OnDeserialized(StreamingContext context)
    {
        // SAMAccountName is not deserialized to any property
        // and so it is added to the extension data dictionary
        string samAccountName = (string)_additionalData["SAMAccountName"];

        Domain = samAccountName.Split('\\')[0];
        UserName = samAccountName.Split('\\')[1];
    }

    public DirectoryAccount()
    {
        _additionalData = new Dictionary<string, JToken>();
    }
}

string json = @"{
  'DisplayName': 'John Smith',
  'SAMAccountName': 'contoso\\johns'
}";

DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);

Console.WriteLine(account.DisplayName);
// John Smith

Console.WriteLine(account.Domain);
// contoso

Console.WriteLine(account.UserName);
// johns
like image 131
Andrew Barrett Avatar answered Sep 28 '22 04:09

Andrew Barrett


You can create a CustomCreationConverter to do what you need to do. Here's a sample (rather ugly, but demonstrates how you may want to go about this):

namespace JsonConverterTest1
{
    public class Mapped
    {
        private Dictionary<string, object> _theRest = new Dictionary<string, object>();
        public int One { get; set; }
        public int Two { get; set; }
        public Dictionary<string, object> TheRest { get { return _theRest; } }
    }

    public class MappedConverter : CustomCreationConverter<Mapped>
    {
        public override Mapped Create(Type objectType)
        {
            return new Mapped();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var mappedObj = new Mapped();
            var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();

            //return base.ReadJson(reader, objectType, existingValue, serializer);
            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.PropertyName)
                {
                    string readerValue = reader.Value.ToString().ToLower();
                    if (reader.Read())
                    {
                        if (objProps.Contains(readerValue))
                        {
                            PropertyInfo pi = mappedObj.GetType().GetProperty(readerValue, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                            var convertedValue = Convert.ChangeType(reader.Value, pi.PropertyType);
                            pi.SetValue(mappedObj, convertedValue, null);
                        }
                        else
                        {
                            mappedObj.TheRest.Add(readerValue, reader.Value);
                        }
                    }
                }
            }
            return mappedObj;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            string json = "{'one':1, 'two':2, 'three':3, 'four':4}";

            Mapped mappedObj = JsonConvert.DeserializeObject<Mapped>(json, new MappedConverter());

            Console.WriteLine(mappedObj.TheRest["three"].ToString());
            Console.WriteLine(mappedObj.TheRest["four"].ToString());
        }
    }
}

So the output of mappedObj after you deserialize the JSON string will be an object with its One and Two properties populated, and everything else put into the Dictionary. Granted, I hard-coded the One and Two values as ints, but I think this demonstrates how you'd go about this.

I hope this helps.

EDIT: I updated the code to make it more generic. I didn't fully test it out, so there may some cases where it fails, but I think it gets you most of the way there.

like image 41
David Hoerster Avatar answered Sep 28 '22 04:09

David Hoerster