Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json .NET Serialization - change the property value

Tags:

json

c#

json.net

Good day!

I am currently using the Newtonsoft Json Serializer through the following code:

        private string serializeAndIgnoreEmail(UserMembership obj)
        {
            var json = JsonConvert.SerializeObject(obj, Formatting.Indented,
                new JsonSerializerSettings() { ContractResolver = new DocumentIdContractResolver() });
            return json;
        }
        private class DocumentIdContractResolver : CamelCasePropertyNamesContractResolver
        {
            protected override List<MemberInfo> GetSerializableMembers(Type objectType)
            {
                return base.GetSerializableMembers(objectType).Where(o => o.Name != "Email").ToList();
            }
        }

Everytime I need to serialize an object I call the 'serializeAndIgnoreEmail' method. I now want to replace the content of each property with it's encrypted version and I don't know where to do this.

My guess would be to override a method in the 'DocumentIdContractResolver', but there are so many CreateBlahBlahBlah ones, that I find it very hard to work with them.

Is this the right approach, to continue modifying the ContractResolver or should I try something else?

Thank you!

like image 819
tony.hegyes Avatar asked Aug 08 '13 10:08

tony.hegyes


People also ask

How does the Jsonproperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is the difference between JSON and serialization?

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). If you serialize this result it will generate a text with the structure and the record returned.

What is serialization of JSON in C#?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects. In this article and code examples, first we will learn how to serialize JSON in C# and then we will learn how to deserialize JSON in C#.

What is a JSON serialization exception?

The exception thrown when an error occurs during JSON serialization or deserialization.


2 Answers

Calling SerializeObject does two things: create a tree of JSON tokens based on the object you specify, and serialize that into a string containing the JSON.

Your best bet would be to do the two steps separately: first ask JSON.NET to provide you with the tree of JSON tokens, then modify the values, then serialize them to JSON.

From the top of my head:

namespace JsonEncryptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var obj = new
                {
                    To = "Some name",
                    Subject = "A Subject",
                    Content = "A content"
                };

            var jsonObject = JObject.FromObject(obj);

            // modify the values. Just doing something here to amuse you.
           var property = jsonObject.Property("Content");
           var value = (string) property.Value;
           property.Value = value.ToLower();

            var json = jsonObject.ToString();

            Console.WriteLine(json);
        }
    }
}
like image 63
Dave Van den Eynde Avatar answered Oct 30 '22 01:10

Dave Van den Eynde


I have not done the exact same thing. But in my case for a web API project, I needed to serialize string names of enum values instead of their numeric values. I did a bit of research and realized that Json formatter converters are empty by default. So I added :

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

In your case, you need to write a custom JsonConverter and add it to the list of converters. You can find a similar example here:

Custom Json Converter

like image 35
Matt Shams Avatar answered Oct 30 '22 00:10

Matt Shams