Search code examples
c#json.netjson.net

C# | Create a json string out of static class fields with values


I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s. Key value pairs saved in string, could be wrapped at the end like

    ResultString = "{ " + resultString + " }";

C# .NET 4.7.2 (console app)


Solution

  • As others have said, a static class is not a good design here.

    However, it is possible to map it back to JSON with some simple reflection:

    public static JObject MapStaticClassToJson(Type staticClassToMap)
    {
        var result = new JObject();
        var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
        foreach (PropertyInfo prop in properties)
        {
            result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
        }
        
        return result;
    }